[英]Copy items from ListBox to CheckedListBox
有很多問題與這個問題恰恰相反,不幸的是,沒有一個問題對我有用。 我有以下代碼可以實現我的目的:
foreach (var item in listBox1.Items)
{
checkedListBox1.Items.Add(item);
}
問題是當我這樣做時,我沒有得到ListBox
內的值,而是System.Data.DataRowView
項。 因此,我的CheckedListBox
正是使用System.Data.DataRowView
字符串填充的,它們都是相同的,並且不顯示實際的字符串值。
編輯 :我以這種方式綁定到ListView
:我有一個DataTable ds
,並且:
listBox1.DataSource = ds;
由於某些未知原因, CheckedListBox
控件的DataSource
, DisplayMember
和ValueMember
屬性是隱藏的。
如果要復制列表框項目文本,則正確的方法是使用ListControl.GetItemText方法,如下所示
foreach (var item in listBox1.Items)
checkedListBox1.Items.Add(listBox1.GetItemText(item));
但是用這種方法很難找到要檢查的源對象 (例如,枚舉CheckedItems時 )。 更好的方法是像這樣定義自己的類
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) });
您需要執行以下操作:
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 });
}
當這些控件綁定到數據源時, 派生ListControl類(如CheckedListBox)顯示的文本由屬性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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.