将项目从 ListBox 复制到 CheckedListBox

Copy items from ListBox to CheckedListBox

有很多问题与此问题相反,不幸的是 none 其中对我有用。我有以下代码来实现我的目的:

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

问题是当我这样做时,我没有得到 ListBox 中的值,而是 System.Data.DataRowView 项中的值。所以我的 CheckedListBox 得到了完全相同的 System.Data.DataRowView 字符串,它们都是相同的并且不显示实际的字符串值。

编辑:我以这种方式绑定到 ListView:我有一个 DataTable ds,并且:

listBox1.DataSource = ds;

您需要进行如下转换:

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

否则你可以这样使用:

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

即使这也可能对您有所帮助(如果您需要文本和值,请像这样使用);

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 });   
   }

derived ListControl classes like a CheckedListBox, when these controls are binded to a datasource, is ruled by the property DisplayMember显示的文字。此 属性 等于表示数据源中 属性(或列名)名称的字符串。

所以在将新项目添加到您的检查列表框之前,我建议写

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

而且不需要创建一个循环来读取源列表框中的所有项目,只需使用相同的数据源就可以了

试试这个:

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

由于某些未知原因,DataSourceDisplayMemberValueMember 属性对于 CheckedListBox 控件是隐藏的。

如果你想复制列表框的项目文本,正确的方法是使用ListControl.GetItemText这样的方法

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

但是这样就很难找到object被选中的来源(例如在枚举CheckedItems时)。更好的方法是像这样定义你自己的 class

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

并使用

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