Thursday, February 16, 2006

Using ASP.NET 2.0 GridView Template Controls

I'm using a GridView control on an ASP.NET 2.0 page. I have added some templated columns so the grid looks like this:-

When the Test button is pressed I want to get the values in the TextBoxes. There are two options:-

Option 1
Set the CommandArgument of the Test button to hold a value indicating the row number. You need to add the following to the Test button's HTML definition

CommandArgument='<%# Container.DataItemIndex %>'

IE7B2 does not render the text above correctly, Firefox is OK, it should look like this :

Then you can get the Row and TextBox contents using this code

protected void GridView1_RowCommand (object sender, GridViewCommandEventArgs e)


if (e.CommandName.ToLower () == "test")


int rowindex = int.Parse (e.CommandArgument.ToString ());

GridViewRow row1 = GridView1.Rows[rowindex];

TextBox tb_percent1 = row1.FindControl ("TextBox1") as TextBox;

TextBox tb_value1 = row1.FindControl ("TextBox2") as TextBox;

TextBox tb_month1 = row1.FindControl ("TextBox3") as TextBox;

TextBox tb_year1 = row1.FindControl ("TextBox4") as TextBox;

Option 2

You can use the following code. With this option you do not need to set the CommandArgument on the button.

protected void GridView1_RowCommand (object sender, GridViewCommandEventArgs e)


if (e.CommandName.ToLower () == "test")


GridViewRow row2 = (GridViewRow) ((Control) e.CommandSource).Parent.Parent;

TextBox tb_percent2 = row2.FindControl ("TextBox1") as TextBox;

TextBox tb_value2 = row2.FindControl ("TextBox2") as TextBox;

TextBox tb_month2 = row2.FindControl ("TextBox3") as TextBox;

TextBox tb_year2 = row2.FindControl ("TextBox4") as TextBox;

No comments: