将DataBound DropDownList添加到DataGrid

时间:2012-01-19 05:54:17

标签: asp.net data-binding datagrid drop-down-menu

我有一个DataGrid绑定到DataView,其中包含一个ID列和ParentID列,我需要用户能够使用{{1}指定一个ParentID (ComboBox)。

现在,我已经将DropDownList添加到DataGrid,如下所示:

DropDownList

在代码隐藏中我有以下方法:

<Columns>
    [...]
    <asp:TemplateColumn HeaderText="Parent" >
        <ItemTemplate>
            <asp:DropDownList ID="ddlParentID" 
                              runat="server" 
                              DataValueField="ID"
                              DataTextField="Short_Description"
                              Width="100%"
                              DataSource="<%# dsDV %> ">
            </asp:DropDownList>
        </ItemTemplate>
    </asp:TemplateColumn>
</Columns>

在表单Load Event上调用Protected dsDV As New DataView Protected Sub PopulateDropDownList() Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(myConnString) Dim comm As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT * FROM myTable", conn) comm.CommandType = CommandType.Text Dim myTableTable As New DataTable conn.Open() myTableTable.Load(comm.ExecuteReader) Me.dsDV = myTableTable.DefaultView End Sub 但是,虽然DDL显示,但它们显示为空,就好像没有进行DataBinding一样。

如何在代码隐藏中将DDL与dataSource正确绑定?或者,如果这不是问题,我该如何正确填写DDL?

更新1

在第一个回答后,我继续尝试了这个(仍然没有运气):

PopulateDropDownMethod

请注意,我还从表单加载事件处理程序中删除了对Protected Sub dg_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgData.ItemDataBound If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then Dim ddl As DropDownList = CType(e.Item.Cells(3).FindControl("ddlParentID"), DropDownList) Me.PopulateDropDownList(ddl) End If End Sub Protected dsDV As New DataView Protected Sub PopulateDropDownList(ddl As DropDownList) Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(myConnString) Dim comm As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT * FROM myTable", conn) comm.CommandType = CommandType.Text Dim myTableTable As New DataTable conn.Open() myTableTable.Load(comm.ExecuteReader) ddl.DataSource = myTableTable.DefaultView ddl.DataBind() End Sub 的调用。

2 个答案:

答案 0 :(得分:0)

您可以在设置数据源后尝试调用ddlParent.DataBind()。

答案 1 :(得分:0)

我不是为什么但是从aspx到aspx.vb的绑定代码修复了这个问题,所以现在看起来都像这样:

<asp:TemplateColumn HeaderText="Parent" >
    <ItemTemplate>
        <asp:DropDownList ID="ddlParentID" runat="server" Width="100%" >
        </asp:DropDownList>
    </ItemTemplate>
</asp:TemplateColumn>

对于代码隐藏,对于每一行:

Dim ddl As DropDownList = CType(e.Item.Cells(3).FindControl("ddlParentID"), DropDownList)
ddl.DataValueField = "ID"
ddl.DataTextField = "Short_Description"
ddl.DataSource = myTable.DefaultView
ddl.DataBind()