当启用Multiselect时,使用ObjectDataSource绑定Listbox/CheckedListBox&#

本文关键字:Listbox CheckedListBox 绑定 ObjectDataSource Multiselect 启用 使用 | 更新日期: 2023-09-27 18:10:01

我目前没有代码来以最好的方式解释我的问题。所以可能会有一些语法错误,可能会留下一些与数据源相关的绑定。

的场景。

我有一个类Customer,它包含一些属性

class Customer
{
          int CustomerId{get;set;} //primary key
          int age{get;set;}
          string name{get;set;}
          Collection<BooksPurchased> booksCollection{get;set;}
} 

我使用一个函数说GetCustomer()返回集合

public Collection<Customer> GetCustomer();

此函数使用ObjectDataSource控件与GridView绑定。

<asp:GridView DataKey="CustomerId">
<columns>
<asp:TemplateField>
     <ItemTemplate><%# Eval('age') %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
     <ItemTemplate><%# Eval('name') %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
     <ItemTemplate>
             <asp:Listbox DataSourceId="availableBooks" SelectedValue='<%# Bind("booksCollection") %>' />
             <asp:ObjectDataSource SelectMethod="GetBooksCollection" TypeName="Books">   
     </ItemTemplate>
</asp:TemplateField>
   </Columns>
</asp:GridView>

此网格再次绑定到ObjectDataSource控件,该控件表GetCustomer()函数来绑定网格。

是我想显示/Update和所有选择的项目绑定在Listbox控件。例如,如果Listbox有10个条目,booksCollection包含3个条目。那么这3个项目应该显示为选中的。当用户更改选择时,这些应该反映在集合本身。

当启用Multiselect时,使用ObjectDataSource绑定Listbox/CheckedListBox&#

就我个人而言,我避免在ASP标记中执行这种操作。因此,我不确定您是否可以单独在标记中绑定图书的完整列表并为每个客户选择图书——当然,SelectedValue属性不是这样做的。

我将这样做:

标记:

<asp:GridView ID="customers" DataKey="CustomerId">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate><%# Eval('age') %></ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate><%# Eval('name') %></ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Listbox ID="books" DataSourceId="availableBooks" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

后台代码:

protected override OnInit(EventArgs e)
{
    base.OnInit(e);
    customers.RowDataBound += new GridViewRowEventHandler(customers_RowDataBound);
}
void customers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Customer currentCustomer = (Customer) e.Row.DataItem;
        Listbox books = (ListBox) e.Row.FindControl("books");
        books.DataSource = GetBooksCollection();
        books.DataBind();
        foreach (BooksPurchased currentBook in currentCustomer.booksCollection)
        {
            if (books.Contains(currentBook))
            {
                books.Selected = true;
            }
        }
    }
}

这段代码并不漂亮,还需要填写一些细节(比如bookspurbought对象的结构),但它应该能让您正确地显示每个客户所选的图书。

当用户在ListBox中选择不同的项目时,管理添加和删除图书有点复杂,每个选项都取决于实现细节(例如:如何存储客户,如果有的话?是立即更新数据库,还是缓存更改,直到用户单击提交按钮?)如果你能提供更多关于这部分的细节,我可能也能帮上忙。