【问题标题】:Creating dynamic DataList controls with ID's based on bound data基于绑定数据创建具有 ID 的动态 DataList 控件
【发布时间】:2011-03-09 00:30:21
【问题描述】:

作为 asp:Checkboxes 没有值这一事实的解决方法,我尝试在 DataList 中动态创建复选框的 ID,以便将主键插入到控件 ID 中。这非常困难。

我在我的 DataList ItemTemplate 中放置了一个 PlaceHolder,然后在 ItemCreated 中我使用string.Format("Checkbox{0}", DataBinder(e.Item.DataItem, "ID")) 创建了复选框。问题是这只适用于非回发条件,因为在回发时 DataItem 为空。当然,ItemDataBound 不会在 PostBack 上调用,所以这也不起作用。

我似乎找不到处理if (IsPostback) dataList.Bind() 不足的好方法,我认为这不是一个好方法。

谁能在这里为我提供任何替代方案?

编辑:

一些附加信息。我刚刚意识到问题的一部分是因为我实际上在 DataList 中有一个 DataList。 DataItem 为 null 的原因是回发时没有数据绑定,并且子数据没有保存到视图状态。

基本上,我正在做的是This,尽管它使用的是DataList 而不是Repeater。因此,在回发时,不会设置 Children 集合,因为在回发时未调用 ItemDataBound。

EDIT2:澄清一下,问题主要是因为嵌套的数据列表。我必须将嵌套数据列表的数据源设置为第一个数据列表的各个行字段的集合字段。在回发时,没有数据绑定,所以它不起作用。

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    您可以使用与我在 this answer 中所写的技术类似的技术 - 在 ItemTemplate 中添加一个常规 CheckBox 和一个 HiddenField 控件,并将 HiddenField 绑定到主键值,例如

    <ItemTemplate>
        <tr>
            <td>
                <asp:CheckBox runat="server" ID="MyCheckBox" AutoPostBack="true" oncheckedchanged="MyCheckBox_CheckedChanged"  />
                <asp:HiddenField runat="server" id="DatabaseKeyHiddenField" Value='<%# Eval("DatabaseKey") %>' />
            </td>
        </tr>
    </ItemTemplate>
    
    protected void MyCheckBox_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox selectedCheckBox;
        DataListItem selectedDataListItem;
        HiddenField databaseKeyHiddenField;
        string databaseKey;
    
        // Cast the sender object to a CheckBox
        selectedCheckBox = (CheckBox)sender;
    
        // Walk up the tree one level so we get the container for both controls
        selectedDataListItem = (DataListItem)selectedCheckBox.Parent;
    
        // Get the HiddenField control ...
        databaseKeyHiddenField = (HiddenField)selectedDataListItem.FindControl("DatabaseKeyHiddenField");
    
        // ... and read the value
        databaseKey = databaseKeyHiddenField.Value;
    
        // Go off and do a database update based on the key we now have
        ...
    }
    

    这是一种解决方法,而不是完全您想要做的,但它有效!

    【讨论】:

    • 虽然您的解决方案可以在单个 DataList 中工作,但它不适用于嵌套的。问题是第二个数据列表是动态创建的,然后它的控件是动态创建的。而且您必须在后面的代码中为第二个数据列表设置数据源,这意味着它不会被序列化为视图状态。所以在回发时,没有要设置的数据源。
    • 其实我错了。这种方法允许我删除代码隐藏复选框的创建,并让模板来做,这样它就会在回发时被序列化。不是一个完美的解决方案,但它确实有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    相关资源
    最近更新 更多