c# - Gridview Binding DropDownList 来自后面的代码

标签 c# asp.net data-binding gridview

我需要将 GridView 与复选框列、下拉列表列和文本框绑定(bind)。就像默认模式是编辑一样。请帮我从后面的代码中绑定(bind)组合框项目。组合框值需要从网络服务中获取。所有网格数据从代码后面绑定(bind)。用户可以更改网格上的数据。

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
        <asp:TemplateField >
                <ItemTemplate >
                    <asp:CheckBox ID="CheckBox1" runat="server" Checked= "<%# Bind('select') %>" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Roles">
                <ItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server" 
                        SelectedValue='<%# Eval("Roles") %>'>
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text="<%# Bind('Name') %>"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

代码隐藏

 protected void Page_Load(object sender, EventArgs e)
{

    DataTable table = new DataTable();
    table.Columns.Add("select", typeof(bool));
    table.Columns.Add("Roles", typeof(string));
    table.Columns.Add("Name", typeof(string));
    table.Rows.Add(true, "Admin", "name1" );
    table.Rows.Add(true, "Admin", "name2");
    table.Rows.Add(true, "user", "name3");
    table.Rows.Add(false, "user", "name4");
    table.Rows.Add(false, "Admin", "name5");
    GridView1.DataSource = table;
    GridView1.DataBind();

}

最佳答案

你可以尝试这样的事情。

<asp:DropDownList ID="DropDownList1" runat="server" 
OnDataBound="DropDownList_OnDataBound"></asp:DropDownList>

protected void DropDownList_OnDataBound(object sender, EventArgs e)

{
   DropDownList ddl = sender as DropDownList;
   if(ddl != null)
   {
        // call web service and 
        // populate ddl.Items
   }
}

关于c# - Gridview Binding DropDownList 来自后面的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5135931/

相关文章:

c# - 如何使用 LINQ 从对象集合中获取最新日期?

c# - 读取 appsettings.json - 字段保持为空

c# - 拖放小部件代码

wpf - 为什么带有转换器的多重绑定(bind)在工具提示中不起作用?

c# - 绑定(bind)到 WPF 中的 TreeView

c# - 如何通过Visual Studio安装项目降级程序?

c# - 如何在没有父类的情况下使用内联变量声明内联对象

c# - 将静态数据添加到 C# 项目

c# - 验证电子邮件

asp.net - winforms中的gridview rowdatabound事件?