如何在checkedlistbox窗口控件中获取已检查项的值成员?

时间:2011-06-29 09:33:49

标签: c# .net winforms

使用以下代码以win形式绑定checkedlistbox。我想获取checkedlistbox中已检查项目的值成员吗?

listCollection = new List<ListItem>();
            listCollection.Add(new ListItem { text = "Manufacturer", value = "1" });
            listCollection.Add(new ListItem { text = "Dealer", value = "2" });
            listCollection.Add(new ListItem { text = "Distributor", value = "3" });
            listCollection.Add(new ListItem { text = "Trader", value = "4" });
            listCollection.Add(new ListItem { text = "Service Provider", value = "5" });
            chkListCategory.DataSource = listCollection;
            chkListCategory.DisplayMember = "text";
            chkListCategory.ValueMember = "value";

3 个答案:

答案 0 :(得分:3)

我不知道ListItem是什么,但我想这是一个看起来像的类:

public class ListItem
{
    public string Text;
    public object Value;

    public ListItem(string text, object value)
    { /*...*/ }
}

因此,将DisplayMember = "text";更改为"Text",将ValueMember = "value";更改为"Value"

chkListCategory.DisplayMember = "Text";//"text"; 
chkListCategory.ValueMember = "Value";//"value";

UI的显示文字为“制造商,经销商,分销商......”

值将为“1,2,3 ......”

获取已检查项目的值成员:

获取已检查项目的值:

//first checked item.
var value = (chkListCategory.CheckedItems[0] as ListItem).Value;

//all checked items.
foreach (var value in chkListCategory.CheckedItems)
{
    Console.WriteLine((value as ListItem).Value);
}

//value at any index in the chkListCategory:
var value = (chkListCategory.Item[index] as ListItem).Value;

答案 1 :(得分:0)

以下代码从数据库中获取一些记录并将其放入CheckedListBox

SqlCommand cmd = new SqlCommand(@"SELECT Code, GenericName FROM tbl_Item", Connection);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        chklItems.DataSource = null; // chklItems is a CheckedListBox
        if (chklItems.Items.Count > 0)
            chklItems.Items.Clear();
        chklItems.DataSource = dt;
        chklItems.DisplayMember = "GenericName";
        chklItems.ValueMember = "Code";


获取已检查项目的值成员

for (int i = 0; i < chklItems.CheckedItems.Count; i++)
        {
            string code = ((DataRowView)chklItems.CheckedItems[i]).Row["Code"].ToString();
        }

答案 2 :(得分:-3)

foreach(DataRowView view in chkListCategory.CheckedItems)
{
    Console.WriteLine(view[chkListCategory.ValueMember].ToString());
}