2011-09-05 99 views
3

我想为GridView中的每个条目添加一个下拉列表。GridView中的DropDownList asp.net

<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="False" 
     onselectedindexchanged="GridView1_SelectedIndexChanged"> 

     <Columns>     
      <asp:TemplateField HeaderText="Bank"> 
      <ItemTemplate> 
       <asp:DropDownList ID="DropDown" 
       AutoPostBack="true" runat="server" DataTextField="Name" DataValueField="Name" 
       > 
       </asp:DropDownList> 
       </ItemTemplate> 
      </asp:TemplateField> 

     </Columns> 
    </asp:GridView> 

在后端我有以下代码为了将数据表绑定到该下拉列表。

DataTable reader = BusinessLayer.BusinessLayerHandler.GetBankList(); 
DropDown.DataSource = reader; 
DropDown.DataTextField = "NAME"; 
DropDown.DataValueField = "NAME"; 
DropDown.DataBind(); 

我的问题是,在网格视图(下拉)创建的下拉列表中没有,如果它不存在后端发现..

我能做些什么?

回答

8

将为GridView中的每个单品创建DropDownList,因此不能为为下拉列表的一个字段。不过,你可以检索单行DropDownList的(例如,在RowDataBoundRowCreated事件)

protected void grid_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if(r.Row.RowType == DataControlRowType.DataRow) 
    { 
    DropDownList dropdown = e.Row.FindControl("DropDown") as DropDownList; 
    if(dropdown != null) 
    { /* your code */ } 
    } 
} 

或者你可以使用DropDownList本身的事件并访问sender参数。

<asp:DropDownList ID="DropDown" OnLoad="dropdownLoad" /> 

protected void dropdownLoad(object sender, EventArgs e) 
{ 
    DropDownList dropdown = sender as DropDownList; 
    if(dropdown != null) 
    { /* your code */ } 
} 
+0

首先你需要检查你正在处理的行的类型。在你试图找到一个下拉菜单之前 - if(e.RowTypeRowType == DataControlRowType.DataRow) –

+0

这不是必须的,但它应该完成,这是正确的......我只是编辑了我的答案。 –

-1

您可以通过grid.findcontrol找到dropdowngrid databound event