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

【1】
<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();  
/////////////////////////////////////////////////////////////////////////////////////////
4   DropDownList drp = sender as DropDownList; // 触发事件的 DropDownList
5    GridViewRow row = drp.NamingContainer as GridViewRow; // GridView 当前行 即时在dropdownlist所在容器里 就是行的信息    
6    row.Style.Add(HtmlTextWriterStyle.BackgroundColor, drp.SelectedValue);
7    Response.Write(row.RowIndex+1);//获取dropdownlist中选定行的行号.
8        //Response.Write(String.Format("选中第 {0} 行", row.RowIndex + 1));
9     DropDownList ddlClass = (DropDownList)sender;
10     string ClassID = ddlClass.SelectedValue.ToString();//获取Dropdownlist中选定值

    }

【2】

<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进行处理。  
  }   

你可能感兴趣的:(GridView)