Programmatically Load a GridView Row in Edit Mode

A user in asp.net forums asked a question about loading a GridView Row programmatically in EditMode. It’s quite simple actually. You just have to set the EditIndex to the row number that needs to be edited and bind the GridView with the datasource. Here’s an example:

C#

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Employee emp = new Employee();
listEmp = emp.GetEmployees();
// Add Row in Edit Mode
GridView1.EditIndex = 3;
// Bind GridView to its Source
this.GridView1.DataSource = listEmp;
this.GridView1.DataBind();
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not Page.IsPostBack) Then
Dim
emp As New Employee()
listEmp = emp.GetEmployees()
' Add Row in Edit Mode
GridView1.EditIndex = 3
' Bind GridView to its Source
Me.GridView1.DataSource = listEmp
Me.GridView1.DataBind()
End If
End Sub

OUTPUT

image

Just remember the EditIndex to RowNumber – 1. So to load Row 4 in EditMode, set the EditIndex to 3. You may also want to check the number of rows before you set the EditMode to avoid Errors.



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

2 comments:

Anonymous said...

Is there a way to make the entire gridview ready for edit?

Suprotim Agarwal said...

Yes there's a way. check this solution - http://aspadvice.com/blogs/azamsharp/archive/2006/11/08/Show-all-GridView-Rows-in-EditMode.aspx