Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get row index in Dropdownlist selectedIndexChanged?

Tags:

c#

asp.net

I'm using a gridview and sqldatasource.

I have a dropdownlist in my gridview with 2 values : Yes and No .

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = GridView1.Rows[e.RowIndex];
    DropDownList ddl = ((DropDownList)row.FindControl("DropdownList1"));
    if(ddl.selectedvalue == "1")
        //etc..
}

I need to get the Row index because this GridViewRow row = GridView1.Rows[e.RowIndex]; is not available in the current event.

like image 769
Jax Avatar asked May 24 '12 19:05

Jax


1 Answers

As @mellamokb has already mentioned, you always get the control that raised an event by the sender argument, you only have to cast it accordingly.

DropDownList ddl = (DropDownList)sender;

If you also need to get a reference to the GridViewRow of the DropDownList(or any other control in a TemplateField of a GridView), you can use the NamingContainer property.

GridViewRow row = (GridViewRow)ddl.NamingContainer;

but I need to get the row index for getting a value from a templatefield who's not a dropdown is a textbox

You can get any control once you have the GridViewRow reference by using row.FindControl("ID") (TemplateField) or row.Cells[index].Controls[0] (BoundField).

For example (assuming there's a TextBox in another column):

TextBox txtName = (TextBox)row.FindControl("TxtName");
like image 98
Tim Schmelter Avatar answered Nov 15 '22 18:11

Tim Schmelter