C# 如何在下拉列表 selectedIndexChanged 中获取行索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10744321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:04:10  来源:igfitidea点击:

How to get row index in Dropdownlist selectedIndexChanged?

c#asp.net

提问by Jax

I'm using a gridview and sqldatasource.

我正在使用 gridview 和 sqldatasource。

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

我的 gridview 中有一个下拉列表,有 2 个值: Yes 和 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.

我需要获取行索引,因为这GridViewRow row = GridView1.Rows[e.RowIndex];在当前事件中不可用。

采纳答案by Tim Schmelter

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.

正如@mellamokb 已经提到的,您始终可以通过 sender 参数获得引发事件的控件,您只需相应地对其进行转换。

DropDownList ddl = (DropDownList)sender;

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

如果您还需要获取GridViewRowDropDownList(或 GridView 的 TemplateField 中的任何其他控件)的引用,您可以使用该NamingContainer属性。

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 GridViewRowreference by using row.FindControl("ID")(TemplateField) or row.Cells[index].Controls[0](BoundField).

GridViewRow通过使用row.FindControl("ID")(TemplateField) 或row.Cells[index].Controls[0](BoundField)获得引用后,您可以获得任何控制 。

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

例如(假设TextBox另一列中有一个):

TextBox txtName = (TextBox)row.FindControl("TxtName");

回答by mellamokb

If all you are looking for is the value of the dropdownlist, that's passed in as the sender:

如果您要查找的只是下拉列表的值,则将其作为以下内容传入sender

DropDownList ddl = sender as DropDownList;
if (ddl.SelectedValue == "1")
   // do something...

回答by deepthi

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