How to handle two-way SqlDataSource binding in ASP.NET ListBox

If I have two lists, with a button between them, how can I update ListBox2 items if ListBox2 items are database binding?

<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" />

Also, if I use SelectionMode = "Multiple", can I update the DataSource with UpdateCommand, which takes one item at a time?

EDIT:

Good to add some clarification:

  • Both lists are a DataBound for unique data (SqlDataSource).
  • I want to add items from ListBox1 to ListBox2 and vice versa when the user clicks a button.
  • I want to be able to add multiple items to a ListBox (suppose multiple selection is enabled)
  • I want to call UpdateCommand in a DataSource.

, , - listBox DataCource UpdateCommand SqlDataSource.Update(). , , , . , , - DataSource ListBox , Bind/Update .

+3
3

- , , DataSource . , , , "", ASP ListItem AppendToDataSource True.

, DataSource # DataSourceID. .

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

#

    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 .

+3

DataBound ListBox2. SQL .

0

it doesn't matter if your list is bound to a datacontext, or you shouldn't use

ListBox1.Items.Add(/*your listBox Item*/);// for example if you have a person listbox you should have - ListBox1.Items.Add(new Person(1,"Nasser","Hajloo");

just remember that you have to add items after binding, I mean

ListBox1.DataSource = myDBList;
ListBox1.DataBind();
//some other code 
ListBox1.Items.Add(new Person(1,"Nasser","Hajloo");
ListBox1.DataBind();
0
source

Source: https://habr.com/ru/post/1727177/


All Articles