Home > ASP .NET > Making ASP .NET Gridview a little less painful

Making ASP .NET Gridview a little less painful

January 28th, 2009 Nizar Leave a comment Go to comments

Isn’t it pain in the neck when you have to write the following for every input control whose value you want to extract from a Gridview:

public static void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
   string firstname = ((TextBox)myGridview.Rows[e.RowIndex].
                                            FindControl("txtFirstname")).Text;
   string lastname = ((TextBox)myGridview.Rows[e.RowIndex].
                                            FindControl("txtLastname")).Text;
 
   //....and so on.. 
}

Well, you can make it a little easier by implementing the following method either in a class that extends GridView or by writing a extension method. In this example, I’ve written it as an extension method.

public static T FindControl<T>(this GridView gridView, string cntrlName, 
                                          int rowIndex)
      where T : Control
{
   return (T)(gridView.Rows[rowIndex].FindControl(cntrlName));
}

Now the code inside my page is little cleaner and easier to write:

public static void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
   string firstname = gridView.FindControl<TextBox>("txtFirstname", e.RowIndex).Text;
   string lastname = gridView.FindControl<TextBox>("txtLastname", e.RowIndex).Text;
 
     //....and so on.. 
}

I admit it’s not something huge but it definitely is a big help when you have to type in that statement for every single control in your Gridview!

I hope that helps some!

Kick It on DotNetKicks.com Shout it
  1. No comments yet.
  1. No trackbacks yet.