如何获得多项目checkedlistbox,c#,winforms的选定值

时间:2011-07-19 18:55:31

标签: c# winforms checklistbox

所以,我有一个checkListBox,我正在尝试获取复选框的值成员。目前,我可以获得一个项目的selectedValue。如果选中了多个项目,我会为每个项目获得相同的selectedValue。

这个框就像这样填充......

SqlConnection cn = new SqlConnection(Properties.Settings.Default.cs);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("usp_getCustomers, cn);
DataSet ds = new DataSet();
da.Fill(ds, "usp_getCustomers");
chkListCustomer.DataSource = ds;
chkListCustomer.DisplayMember = "usp_getCustomers.name";
chkListCustomer.ValueMember = "usp_getCustomers.id";
chkListCustomer.SelectedIndex = -1;

点击按钮,这就是我正在做的尝试并获取所选值。它为我提供了一个项目的正确ID,但是如果选中了多个项目,它会为所有项目提供相同的ID。

foreach (int indexChecked in chkListCustomer.CheckedIndices)
{
    MessageBox.Show("Index#: " + indexChecked.ToString() + ", is checked. Checked state is:" + chkListCustomer.SelectedValue.ToString()  + ".");   
}

示例输出是:

"Index#: 1, is checked. Checked state is:984"  
"Index#: 2, is checked. Checked state is:984"  
"Index#: 3, is checked. Checked state is:984" 

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

试试这个:

foreach (int indexChecked in chkListCustomer.CheckedIndices)
{
    MessageBox.Show("Index#: " + indexChecked.ToString() +
        ", is checked. Checked state is:" +
        chkListCustomer.Items[indexChecked].ToString()  + ".");   
}

答案 1 :(得分:1)

如果您实际上不需要索引,则只需使用the CheckedItems property

foreach (DataRowView checkedItem in chkListCustomer.CheckedItems)
{
    MessageBox.Show("Checked item: "
        + checkedItem[chkListCustomer.ValueMember].ToString()
        + ".");
}

答案 2 :(得分:0)

你应该使用

chkListCustomer.GetItemCheckState(indexChecked).ToString()

而不是

chkListCustomer.SelectedValue.ToString()

有关CheckedIndicesCheckedListBox Class的有关MSDN的更多信息。

您也可以遍历.Items属性:

foreach(object itemChecked in chkListCustomer.CheckedItems) {
    // Use the IndexOf method to get the index of an item.
    MessageBox.Show("Item with title: \"" + itemChecked.ToString() + 
                    "\", is checked. Checked state is: " + 
        chkListCustomer.GetItemCheckState(chkListCustomer.Items.IndexOf(itemChecked)).ToString() + ".");
    MessageBox.Show(itemChecked.ToString())
}

答案 3 :(得分:0)

修改了Ahmad Mageed在SO on this post找到的一段代码。这给了我每个

    foreach (object itemChecked in chkListPatients.CheckedItems) 
    {
        DataRow row = (itemChecked as DataRowView).Row;
        string id = row[0].ToString();
        MessageBox.Show(id);
    }