怎样在GridView中的DropDownList选项改变的时候获取GridView中的DataKeys.Value的二种方法

<asp:GridView ID="GridView2" runat="server"> <Columns> <asp:TemplateField> <asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server" DataKeyNames="ID"> <asp:ListItem Value="1001">选项1</asp:ListItem> <asp:ListItem Value="1002">选项2</asp:ListItem> <asp:ListItem Value="1003">选项3</asp:ListItem> <asp:ListItem Value="0">选项4</asp:ListItem> </asp:DropDownList> </asp:TemplateField> </Columns> </asp:GridView>

 

正常代码如上,一般的情况下,我们会采用

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID" > <Columns> <asp:TemplateField> <ItemTemplate> <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" onselectedindexchanged="DropDownList1_SelectedIndexChanged" > <asp:ListItem Text="选项1" Value="1001" Selected="False" ></asp:ListItem> <asp:ListItem Text="选项2" Value="1002" Selected="False"></asp:ListItem> <asp:ListItem Text="选项3" Value="1003" Selected="False"></asp:ListItem> <asp:ListItem Text="选项4" Value="0" Selected="False"></asp:ListItem> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> <asp:BoundField ShowHeader="true" DataField="ID" HeaderText="ID" /> <asp:BoundField ShowHeader="true" DataField="name" HeaderText="姓名" /> </Columns> </asp:GridView>

 

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { DropDownList DropDownList1 = sender as DropDownList; int index = (DropDownList1.NamingContainer as GridViewRow).RowIndex; string id = GridView1.DataKeys[index].Value.ToString(); }

 

 

而下这一种,可以更直接的得到想要的值

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" ABCD='<%# Eval("primary_field") %>'>

 

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { DropDownList dr = sender as DropDownList; string keyValue=dr.Attributes["ABCD"]; //根据keyValue进行处理。 }

 

 

此内容转自CSDN上一个提问帖的回复

你可能感兴趣的:(server,object,String,asp)