以编程方式填充下拉菜单时,如何将DropdownList的SelectedValue绑定到DataSoruce?

问题描述

我有一个GridView。当我连续进入编辑模式时,我希望其中一列成为下拉菜单。我的初稿包括

            <asp:TemplateField HeaderText="Type">
            <ItemTemplate>
                <%# Eval("type_name") %>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:DropDownList ID="ctlItemType" runat="server" datasourceid="dsItemTypes"
                  DataTextField="name" DataValueField="id" 
                  selectedvalue='<%# Bind("item_type_id") %>' />
            </EditItemTemplate>
        </asp:TemplateField>

我应该澄清一下,我的数据源包括“ type_name”作为类型的名称和“ item_type_id”作为与该名称相对应的ID。效果很好。很好。

但是我需要根据有关记录的其他数据来限制下拉列表中出现的值。好的,我删除了datasourceid,而是使用代码填充下拉列表:

Private Sub ItemsGridView_RowDataBound(sender As Object,e As GridViewRowEventArgs) 
    Handles ItemsGridView.RowDataBound
    If e.Row.RowState = DataControlRowState.Edit Then
        Dim ctlItemType As DropDownList = e.Row.FindControl("ctlItemType")

        Dim parent_id = ItemsGridView.DataKeys(e.Row.RowIndex).Values(1)
        ctlItemType.DataSource = ItemTypeActions.List(parent_id)
        ctlItemType.DataBind()
    End If
End Sub

我认为这是由于“未找到SelectedValue”错误而炸毁的,因为它试图在填充值之前设置选定的值。

所以我也尝试在代码中设置SelectedValue。在上面的DataBind之后,我添加了:

            ctlItemType.SelectedValue = DataBinder.Eval(e.Row.DataItem,"item_type_id")

当我进入编辑模式时,它显示得很好,但是当我单击“更新”时,它会爆炸,因为item_type_id并未包含在传递给更新功能的参数列表中。因为没有绑定,所以只设置了一个评估值。

那么我该如何做呢?有没有办法用代码将控件绑定到数据源?我可以找到与等价的DataBinder.Eval之类的东西。还是...什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)