开发者

Transferring data from one list box to another c#

Ok so I have 2 list boxes one is connected to a database the other isnt.

I want to be 开发者_C百科able to send the selected item from the listbox connected to the database to the one that isnt.

Ive written this code

listBox2.Items.Add(listBox1.SelectedItem);

But instead of copyin the item i get "

System.Data.DataRowView

Anyone havin any advice?


I'm not near my VS install to check the .NET library, but I'd hazard a guess you need a further attribute to get the value, such as listBox1.SelectedItem.Value.


I made this simple program:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
        listBox1.Items.Add("1");
        listBox1.Items.Add("2");
        listBox1.Items.Add("3");
    }

    void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        listBox2.Items.Add(listBox1.SelectedItem);
    }
}

and it works without problems. So I think that your program doesn't work because the type of your items is System.Data.DataRowView and cannot be converted to a string.


private void CopySelItems(ListBox from, ListBox to)
    {
        for (int i = 0; i < from.SelectedItems.Count; i++)
        {
            to.Items.Add(from.SelectedItems[i].ToString());
        }


    }


Can you show the code of first and second lsibox declaration? Other controls have properties like DisplayName and ValueName - the set what column from the datarow will be displayed in the listbox and what will be treated as a value. In your case problem is that the second lisbox does not know what column should be displayed in it.

Updated: When listBox2.Items.Add(listBox1.SelectedItem) executes actually original data row (which came from the DB) is copied to the second listbox. If you want to have the other listbox not conneted to the values got from the DB you need to create copy of them before putting in the second listbox.


this is the simplest way to load a listbox to another list box and at the same time remove the data from the sorce listbox

int mCount = ListBox1.Items.Count;
for (int i = 0; i <= mCount - 1; i++)
{
    if (ListBox1.Items[i] == ListBox1.SelectedItem)
    {
        ListBox2.Items.Add(ListBox1.SelectedItem);
        ListBox1.Items.Remove(ListBox1.SelectedItem);
        mCount=mCount - 1;
        i=i - 1;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜