如何绑定一个下拉列表在gridview? [英] how to bind a dropdownlist in gridview?

查看:95
本文介绍了如何绑定一个下拉列表在gridview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

 < asp:TemplateField HeaderText =XYZ> 
< ItemTemplate>
< asp:DropDownList runat =serverID =MyDDDataSourceId =MyDataSource/>
< / ItemTemplate>
< / asp:TemplateField>

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

 < asp:DropDownList runat =serverDataSource = '<%#GetDropDownData(Container)%>'DataTextField =TextDataValueField =Value/> 

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



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

  protected void GridView_RowDataBound(Object sender,GridViewRowEventArgs e)
{

if(e.Row.RowType == DataControlRowType.DataRow)
{
//找到下拉列表(在第3列中说)
var dd = e.Row.Cells [2] .Controls [0]作为DropDownList;
if(null!= dd){
// bind it
}

/ *
//如果是模板字段,请使用FindControl
dd = e.Row.Cells [2] .FindControl(MyDD)作为DropDownList;
* /
}

}


I have a gridview in which every row contains a dropdownlist. I want to bind every dropdownlist dynamically. Can someone tell me how can i do it. Thanks in Advance

解决方案

If you are using template column then you can bind your drop-down from mark-up using data-binding expressions. For example,

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

Above is assuming that your drop-down data in constant across rows. If it is changing then you can use data-binding expression such as

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

GetDropDownData will be a protected method in code-behind that will return the data (data-table, list, array) for the given row.

You can use GridView.RowDataBound event (or RowCreated event) in code-behind to fill drop-downs. For example,

  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;
      */
    }

  }

这篇关于如何绑定一个下拉列表在gridview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆