How to get row index in dropdownlist selectedIndexChanged?

I am using gridview and sqldatasource.

I have a dropdown in my gridview with two 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]; not available in the current event.

+6
source share
3 answers

As mentioned in @mellamokb, you always get the control that raised the event by the sender argument, you only need to direct it accordingly.

 DropDownList ddl = (DropDownList)sender; 

If you also need to get a link to the GridViewRow DropDownList (or any other control on the TemplateField GridView), you can use the NamingContainer .

 GridViewRow row = (GridViewRow)ddl.NamingContainer; 

but I need to get the row index to get the value from the template field, which is not a combo box is a text field

You can get any control if you have a GridViewRow link using row.FindControl("ID") (TemplateField) or row.Cells[index].Controls[0] (BoundField).

For example (suppose a TextBox in another column):

 TextBox txtName = (TextBox)row.FindControl("TxtName"); 
+19
source

If all you are looking for is the value of a dropdown that passed as sender :

 DropDownList ddl = sender as DropDownList; if (ddl.SelectedValue == "1") // do something... 
+4
source
 Protected Sub ddlneedlocationcmf_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Dim gvrow As GridViewRow = CType(sender, DropDownList).NamingContainer Dim rowindex As Integer = CType(gvrow, GridViewRow).RowIndex End Sub 
+1
source

Source: https://habr.com/ru/post/916601/


All Articles