无法从后面的代码加载 FormView 上的 DropDownList?

tbo*_*one 5 .net asp.net formview drop-down-menu

我有一个 UserControl,包含一个 FormView,包含一个 DropDownList。FormView 绑定到数据控件。

像这样:

<asp:FormView ID="frmEdit" DataKeyNames="MetricCode" runat="server" DefaultMode="Edit" DataSourceID="llbDataSource" Cellpadding="0" >
    <EditItemTemplate>
        <asp:DropDownList ID="ParentMetricCode"  runat="server" SelectedValue='<%# Bind("ParentMetricCode") %>' />
    </EditItemTemplate>
<asp:FormView>
Run Code Online (Sandbox Code Playgroud)

我正在尝试从代码隐藏填充 DropDownList。如果这不包含在 FormView 中,我通常只会在 Page_Load 事件中执行它。但是,这在 FormView 中不起作用,只要我尝试这样做,访问代码中的下拉列表,即:

theListcontrol = CType(formView.FindControl(listControlName), ListControl)  
Run Code Online (Sandbox Code Playgroud)

...调用FormView的数据绑定机制,当然,它试图将DropDownList绑定到底层数据源,导致**'ParentMetricCode'有一个无效的SelectedValue,因为它不存在于列表中项目。“参数名称:值...”错误,因为尚未填充 DropDownList。

我尝试在 FormView 的 DataBinding() 事件中执行加载,但是:

theListcontrol = CType(formView.FindControl(listControlName), System.Web.UI.WebControls.ListControl)
Run Code Online (Sandbox Code Playgroud)

...失败,因为此时 FormView.Controls.Count = 0。

这是不可能的吗?(我不想使用辅助 ObjectDataSource 将下拉列表绑定到)

tbo*_*one 1

好的,找到了“一个”解决方案:
1. 从事件中调用 DDL 填充函数FormView_ItemCreated
2. 修改代码以填充 DDL,如下所示:

Public Overloads Shared Sub BindListControl(Of theLLBLgenEntityType As EntityBase) _   
        (ByVal formView As FormView, _
        ByVal listControlName As String, _
        ByVal theCollection As CollectionCore(Of theLLBLgenEntityType), _
        ByVal DataValueField As EntityField, _
        ByVal DataTextField As EntityField, _
        ByVal IncludeEmptyItem As Boolean)

    If formView.CurrentMode = FormViewMode.Edit Then
        Dim theListcontrol As System.Web.UI.WebControls.ListControl
        theListcontrol = CType(formView.FindControl(listControlName), System.Web.UI.WebControls.ListControl)

    For Each entity As theLLBLgenEntityType In theCollection
        theListcontrol.Items.Add(New ListItem(entity.Fields(DataTextField.Name).CurrentValue.ToString, entity.Fields(DataValueField.Name).CurrentValue.ToString))
    Next

    If IncludeEmptyItem Then 
        theListcontrol.Items.Insert(0, New ListItem("", ""))
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

它似乎基本上可以归结为,您不能在运行时以编程方式在 FormView 中执行额外的“数据绑定”。

(有人知道为什么我的代码格式在这篇文章中全部搞砸了吗?)

更新

该解决方案引发了另一批与插入新项目相关的问题。经过一番折腾后,我终于找到了解决这个问题的方法。此时,我基本上建议要么完全避免 FormView 控件,要么绝对避免以编程方式更改绑定控件。希望对每个 DropDownList 使用单独的数据控件可能效果更好,但这也可能是一厢情愿的想法。