简体   繁体   中英

Add selected item from a bound listbox to a unbound listbox

i want to add selected item from a data bounded listbox (listbox1) to another listbox (listbox2)

Here is the code on a click event of a button.

private void btnrgt_Click(object sender, EventArgs e)
{
     string x = listBox1.SelectedItem.ToString();
     listBox2.Items.Add(x.ToString());
     txttestno.Text = listBox2.Items.Count.ToString();
}

When i run this code System.data.datarowview get displayed in the listbox2.

Kindly help. thank you in advance.

On click button use below code.

protected void btnGo_Click(object sender,EventArgs e) {
    string x = ListBox1.SelectedItem.Text;
    ListBox2.Items.Add(x);
}

When you bind a ListBox datasource to a DataTable every item inside the ListBox is a DataRowView , not a simple string. In the ListBox you see a string displayed because you set the DisplayMember property of the ListBox with the name of a column in that DataRowView.

So, taking the current SelectedItem doesn't return a string but a DataRowView and calling ToString() for a DataRowView returns the full qualified name of the class (System.Data.DataRowView).

You need something like this

private void btnrgt_Click(object sender, EventArgs e)
{
     DataRowView x = listBox1.SelectedItem as DataRowView;
     if ( x != null)
     {
          listBox2.Items.Add(x["NameOfTheColumnDisplayed"].ToString());
          txttestno.Text = listBox2.Items.Count.ToString();
     }
}

EDIT
It is not clear what is the source of the error stated in your comment below, however you could try to avoid adding an item from the first listbox to the second one if that item exists in the second listbox with code like this

private void btnrgt_Click(object sender, EventArgs e)
{
     DataRowView x = listBox1.SelectedItem as DataRowView;
     if ( x != null)
     {
          string source = x"NameOfTheColumnDisplayed".ToString();
          if(!listbox2.Items.Cast<string>().Any(x => x == source))
          {
              listbox2.Items.Add(source);
              txttestno.Text = listBox2.Items.Count.ToString();
          }
     }
}

This solutions works if your second listbox is really populated adding simple strings to its Items collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM