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.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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