Gridview绑定来自代码的DropDownList

时间:2011-02-27 21:02:09

标签: c# asp.net data-binding gridview

我需要使用复选框列,droupdown列和文本框绑定网格视图。它就像默认模式是编辑。请帮我绑定代码背后的组合框项目。组合框值需要从Web服务获取。从后面的代码绑定的所有网格数据。用户可以更改网格上的数据。

  <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();

}

1 个答案:

答案 0 :(得分:3)

你可以尝试这样的事情。

<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
   }
}