【问题标题】:how to bind a dropdownlist in gridview?如何在gridview中绑定下拉列表?
【发布时间】:2011-11-11 20:30:50
【问题描述】:

我有一个gridview,其中每一行都包含一个下拉列表。我想动态绑定每个下拉列表。有人可以告诉我我该怎么做。提前致谢

【问题讨论】:

    标签: asp.net gridview drop-down-menu


    【解决方案1】:

    如果您使用的是模板列,那么您可以使用数据绑定表达式从标记中绑定下拉列表。例如,

    <asp:TemplateField HeaderText="XYZ">
      <ItemTemplate>
        <asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
      </ItemTemplate> 
    </asp:TemplateField>
    

    以上假设您的下拉数据在各行中保持不变。如果它正在改变,那么您可以使用数据绑定表达式,例如

    <asp:DropDownList runat="server" DataSource='<%# GetDropDownData(Container) %>' DataTextField="Text" DataValueField="Value"  />
    

    GetDropDownData 将是代码隐藏中的受保护方法,它将返回给定行的数据(数据表、列表、数组)。

    您可以在代码隐藏中使用 GridView.RowDataBound 事件(或 RowCreated 事件)来填充下拉菜单。例如,

      protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
    
        if(e.Row.RowType == DataControlRowType.DataRow)
        {
          // Find the drop-down (say in 3rd column)
          var dd = e.Row.Cells[2].Controls[0] as DropDownList;
          if (null != dd) {
             // bind it
          }
    
          /*
          // In case of template fields, use FindControl
          dd = e.Row.Cells[2].FindControl("MyDD") as DropDownList;
          */
        }
    
      }
    

    【讨论】:

    • RowCreated 事件怎么样?有理由更喜欢其中一个吗?
    • @Tim,RowCreated 也可以。但是,我相信如果您只是第一次绑定网格(而不是在回发时),RowCreated 肯定会在每次回发时触发,而不是RowDataBound(我在这里不是 100% 确定)。所以在这种情况下,我们可以依靠视图状态来填充下拉菜单。就个人而言,我更喜欢标记路线。
    • 这是假设您在代码中声明了 SQL 实例。如果您已经在后面的代码中绑定了网格视图,则需要有不同的解决方案,因为您将无法使用 DataSourceId="MyDataSource"
    【解决方案2】:

    除了建议的方法之外,您还可以通过以下方式将您的控件绑定到您的标记中:

    <asp:GridView ID="MyGrid" runat="server" DataSourceID="MyDataSource1">
        <Columns>
            <asp:TemplateField>
                <EditItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind ("CustomerId") %>' DataSourceID="CustomersDataSource" DataTextField="CustomerName" DataValueField="CustomerId" >
                    </asp:DropDownList>
                </EditItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    

    【讨论】:

    • 你能说明这将如何更新并显示在 ItemTemplate 的标签中吗?
    【解决方案3】:
    protected void gvSalesAppData_RowDataBound(Object sender, GridViewRowEventArgs e)
    
        {
    
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
    
                DropDownList ddlCurrentPhase = (DropDownList)e.Row.FindControl("ddlCurrentPhase");
                DropDownList ddlProductFamily = (DropDownList)e.Row.FindControl("ddlProductFamily");
                DropDownList ddlProductGroup = (DropDownList)e.Row.FindControl("ddlProductGroup");
                DropDownList ddlETProgramManager = (DropDownList)e.Row.FindControl("ddlETProgramManager");
                DropDownList ddlPLMForTheProduct = (DropDownList)e.Row.FindControl("ddlPLMForTheProduct");
    
                TrackingToolObj.BindCurrentPhases(ddlCurrentPhase);
                TrackingToolObj.BindCurrentPhases(ddlProductFamily);
                TrackingToolObj.BindProductGroups(ddlProductGroup);
                TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlETProgramManager, (int)OSAEnums.RoleTypes.ProgramManager, false);
                TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlPLMForTheProduct, (int)OSAEnums.RoleTypes.PLM, false);
    
    
            }
    
        }
    

    【讨论】:

      【解决方案4】:

      绑定 GridView

      下面是 GridView 控件与数据绑定的代码。

      C#

      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack) 
         {
           this.BindData();   
         }
      } 
      
      private void BindData()
      {
         string query = "SELECT top 10 * FROM Customers";    
         SqlCommand cmd = new SqlCommand(query);    
         gvCustomers.DataSource = GetData(cmd);    
         gvCustomers.DataBind(); 
      }
      
      private DataTable GetData(SqlCommand cmd)
      {    
          string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;    
          using (SqlConnection con = new SqlConnection(strConnString))   
          {        
             using (SqlDataAdapter sda = new SqlDataAdapter())     
             {            
                cmd.Connection = con;            
                sda.SelectCommand = cmd;            
                using (DataTable dt = new DataTable())  
                {                
                    sda.Fill(dt);                
                    return dt;
                }     
             }   
          }
      }
      

      【讨论】:

      • 请编辑您的答案并格式化代码以使其可读
      • 说实话,这是一种愚蠢的做法。如果你在一个gridview 中有500 行,你要查询一个数据库500 次?当我必须这样做时,我用下拉列表中项目的数据填充数据集,如上所示,在 RowDataBound 事件中,将 DataSet 绑定到下拉列表。
      【解决方案5】:

      这是你的网格视图

      <asp:GridView ID="grvExcelData" runat="server" onrowdatabound="GridView2_RowDataBound">
          <HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                       <asp:DropDownList ID="DrdDatabase" Width="100px" runat="server">
                       </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
      

      你的RowDataBound gridview 事件将是

          protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
          {
             string cities = "maxico,chennai,newdelhi,hongkong";
             string [] arr = cities.Split(',');
          // Instead of string array it could be your data retrieved from database.
              if (e.Row.RowType == DataControlRowType.DataRow)
              {
                  DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
                  foreach (string colName in arr )
                      ddl.Items.Add(new ListItem(colName));
              }
          }
      

      【讨论】:

      • 这看起来不像是绑定到数据库,而是附加到一组城市。如果用户对下拉菜单进行了更改,这将如何更新数据库?
      猜你喜欢
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2015-08-15
      • 1970-01-01
      相关资源
      最近更新 更多