Copy items from ListBox to CheckedListBox

不问归期 提交于 2020-01-06 19:35:41

问题


There are many questions that ask the opposite of this question, unfortunately none of them have worked for me. I have the following code to achieve my purpose:

foreach (var item in listBox1.Items)
{
    checkedListBox1.Items.Add(item);
}

The problem is that when I do this, I don't get the values inside the ListBox, rather the System.Data.DataRowView items. So my CheckedListBox gets populated with exactly this, System.Data.DataRowView strings, which are all the same and don't show the actual string value.

Edit: I bind to the ListView this way: I have a DataTable ds, and:

listBox1.DataSource = ds;

回答1:


Try this:

foreach (var dataRowView in listBox1.Items.OfType<DataRowView>())
{
     checkedListBox1.Items.Add(dataRowView[0].ToString());
}



回答2:


For some unknown reason, DataSource, DisplayMember and ValueMember properties are hidden for CheckedListBox control.

If you want to copy the the list box items text, the correct way is to use ListControl.GetItemText method like this

foreach (var item in listBox1.Items)
    checkedListBox1.Items.Add(listBox1.GetItemText(item));

But this way it will be hard to find which source object is checked (for instance when enumerating CheckedItems). A better way would be to define your own class like this

class MyListItem
{
    public object Value;
    public string Text;
    public override string ToString() { return Text; }
}

and use

foreach (var item in listBox1.Items)
    checkedListBox1.Items.Add(new MyListItem { Value = item, Text = listBox1.GetItemText(item) });



回答3:


The text displayed by derived ListControl classes like a CheckedListBox, when these controls are binded to a datasource, is ruled by the property DisplayMember. This property equals to a string representing the name of a property (or a columnname) in the datasource.

So before adding the new items to your checkedlistbox I suggest to write

checkedListBox1.DataSource = listBox1.DataSource       
checkedListBox1.DisplayMember = listBox1.DisplayMember
checkedListBox1.ValueMember = listBox1.ValueMember

And no need to create a loop reading all the items from the source listbox, just use the same datasource and your are ready




回答4:


You need to do a cast like the following :

foreach (var item in listBox1.Items)
 {
    checkedListBox1.Items.Add((ListItem)item);   
 }

or else you can use like this:

foreach (ListItem item in listBox1.Items)
 {
     checkedListBox1.Items.Add(item);   
 }

even this also may help you(use like this if you want text and value);

for(int i=0;i<listBox1.Items.Count-1;i++)
   {
      checkedListBox1.Items.Add(new ListItem() { Text = listBox1.Items[i].Text, Value = listBox1.Items[i].Text });   
   }


来源:https://stackoverflow.com/questions/34588605/copy-items-from-listbox-to-checkedlistbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!