gpt4 book ai didi

asp.net - 如何处理 ASP.NET ListBox 上 SqlDataSource 的双向绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 16:07:28 25 4
gpt4 key购买 nike

如果我有两个列表框,它们之间有一个按钮,如果 ListBox2 的项目是数据绑定(bind)的,我如何更新 ListBox2 的项目?

<asp:ListBox runat="server" ID="ListBox1" DataSourceID="DataSource1"
DataTextField="Name" DataValueField="ID" SelectionMode="Multiple" />

<asp:Button runat="server" ID="addButton" onClick="addButton_Click" />

<asp:ListBox runat="server" ID="ListBox2" DataSourceID="DataSource2"
DataTextField="Name" DataValueField="ID" SelectionMode="Multiple" />

此外,如果我使用 SelectionMode="Multiple",我是否能够使用一次获取一项的 UpdateCommand 来更新数据源?

编辑:

好的,添加一些说明:

  • 两个列表框都通过数据绑定(bind)到唯一数据 (SqlDataSource)。
  • 我想在用户单击按钮时将项目从 ListBox1 添加到 ListBox2,反之亦然。
  • 我希望能够向列表框添加多个项目(假设已启用多项选择)
  • 我希望触发数据源上的 UpdateCommand。

到目前为止,我能够实现此目的的唯一方法是手动从第一个列表框中获取每个项目并将其作为参数添加到 DataSource 的 UpdateCommand 中,然后手动调用 SqlDataSource.Update() 方法。这是可行的,但这意味着我要么需要传递一个分隔字符串以进行多个选择,要么打开多个连接。我正在寻找的是一种更新 ListBox 上的数据源的方法,一旦完全更新,然后调用绑定(bind)/更新并将数据保留回数据库。

最佳答案

第一个问题是您要添加的项目是在绑定(bind)的静态或动态数据源之外。如果您想要添加几个始终相同的项目(例如“None”选项),那么您可以将其作为 ListItem 添加到 ASP 中,并将 AppendToDataSource 属性设置为 True。

如果您想要随数据绑定(bind)值一起动态插入值,则可以将 DataSource 值设置为 C# 函数,而不设置 DataSourceID。它看起来像这样。

<asp:ListBox runat="server" ID="ListBox2" DataSource='<%# myFunc() %>'
DataTextField="Name" DataValueField="ID" SelectionMode="Multiple" />

然后在您的 C# 代码文件中

    protected ListItem[] myFunc()
{
ListItem[] retVals;

//write your code here to get your data from DataSource2 and whatever other sources you need

//then create a ListItem for each row of data you want to show,
//set the text and the value attributes and return an array of all the values in the order you want

return retVals;
}

这将允许您保留您可能已经开发的任何 DataBind 调用功能,因为每次调用对象的 DataBind 方法时都会调用此函数。

关于asp.net - 如何处理 ASP.NET ListBox 上 SqlDataSource 的双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1997038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com