7 Kasım 2008 Cuma

How to access gridview controls/fields

Sick and tired of trying to access controls and fields in GridView?
Here you can find some solutions written in C#:



Accessing datakey within RowCommand when an image button (template field) is clicked

ImageUrl="..." CommandName="..."
CommandArgument=""/>


string id =GridView1.DataKeys[Convert.ToInt32
(e.CommandArgument)].Values[0].ToString();

Accessing an image button (template field) within RowCommand():
int index=Convert.ToInt32(e.CommandArgument.ToString());
ImageButton b = (ImageButton)GridView1.Rows[index].
FindControl("ImageButton1");


Accessing an image button (non-template field):
ImageButton b =(ImageButton)e.Row.Controls[0].Controls[0];

Accessing a dropdownlist (template field):
DropDownList ddl =(DropDownList)e.Row.FindControl("DropDownList1");

Accessing a dropdownlist within RowUpdating():
DropDownList ddl = (DropDownList)
GridView.Rows[GridView.EditIndex].
FindControl("DropDownList1");


Finding the first datakey of the selected row within RowCommand():
string id = ((GridView)e.CommandSource).DataKeys
[Convert.ToInt32(e.CommandArgument.ToString())].
Values[0].ToString();


//gridviews may have multiple datakeys. You can specify them in the datakeynames field separating with commas and access them with array indices.

Another tip:

For a button inside the GridView, you can give "Select" as commandname, so that selectedindexchanged is fired, when the button is pressed. Then you can easily access controls or selected row indices with GridView.SelectedIndex or GridView.SelectedRow.


If useful please rate:

Hiç yorum yok: