如何从CheckedListBox中获取选中项的值?

32

我在C#的WinForm中使用了CheckedListBox控件。我已经将此控件绑定如下所示-

chlCompanies.DataSource = dsCompanies.Tables[0];
chlCompanies.DisplayMember = "CompanyName";
chlCompanies.ValueMember = "ID";

我可以获取被选中项的索引,但如何获取被选中项的文本和值呢?或者说如何枚举CheckedItems并访问Text和Value?

感谢分享你的时间。


无论数据源的类型是DataTable还是List,项目的基础Value应该根据ValueMember计算,而不考虑项目的类型,可以是DataRowViewobject或简单的数据类型。 此帖子分享了一般解决方案。 - Reza Aghaei
9个回答

40

将其转换回原始类型,如果您绑定了一个表,则该类型将是DataRowView,然后您可以从相应的列中获取Id和Text:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
     DataRowView castedItem = itemChecked as DataRowView;
     string comapnyName = castedItem["CompanyName"];
     int? id = castedItem["ID"];
}

我的朋友,我觉得你没有仔细看我的问题。我正在使用CheckedListBox。我不需要任何选择,而是想要选中的项目。该属性只提供所选项目的值。 - IrfanRaza
@w69rdy:CheckedItems 属性是一个 objects 数组。object 没有 SelectedValue 属性,它们可以是任何东西。 - Evan Mulawski
@w69rdy:我得到了castedItem为空的情况。 - IrfanRaza
@w69rdy:我找到了解决方案。我只是用 DataRowView 替换了 DataRow。现在它可以工作了。你能否请更新你的解决方案。 - IrfanRaza
@w69rdy:请更新您的答案,将DataRow更改为DataRowView。现在它可以工作了。我接受了您的解决方案。 - IrfanRaza

14

编辑:我有点晚意识到它绑定了一个DataTable。在这种情况下,思路是相同的,你可以将其转换为 DataRowView,然后获取其 Row 属性以获取一个 DataRow,如果你想要使用该类进行操作。

foreach (var item in checkedListBox1.CheckedItems)
{
    var row = (item as DataRowView).Row;
    MessageBox.Show(row["ID"] + ": " + row["CompanyName"]);
}

您需要将项目转换为其强类型等效项,或使用 System.Data.DataSetExtensions 命名空间来使用下面演示的 DataRowExtensions.Field 方法:

foreach (var item in checkedListBox1.CheckedItems)
{
    var row = (item as DataRowView).Row;
    int id = row.Field<int>("ID");
    string name = row.Field<string>("CompanyName");
    MessageBox.Show(id + ": " + name);
}
您需要将对象强制转换为您的类类型后才能访问其属性。
foreach (var item in checkedListBox1.CheckedItems)
{
    var company = (Company)item;
    MessageBox.Show(company.Id + ": " + company.CompanyName);
}

或者,您可以使用 OfType 扩展方法,在循环中不需要显式转换即可获取强类型结果:

另外,您可以使用 OfType 扩展方法,在循环中获取强类型结果,而无需显式进行转换。

foreach (var item in checkedListBox1.CheckedItems.OfType<Company>())
{
    MessageBox.Show(item.Id + ": " + item.CompanyName);
}

11

谢谢Evan!但我的问题是如何获取所选项目的关联ID? - IrfanRaza
@IrfanRaza:请查看我的编辑代码示例。您需要将每个已选中的项目强制转换为您的自定义数据类型,以访问其特定属性。 - Evan Mulawski

2
foreach (int x in chklstTerms.CheckedIndices)
{
    chklstTerms.SelectedIndex=x;
    termids.Add(chklstTerms.SelectedValue.ToString());
}

1
尝试以下方法以获取CheckedListBox中所有已选项:
在此情况下,ths value是一个字符串,但它可以与其他类型的对象一起运行。
for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
    if (myCheckedListBox.GetItemChecked(i) == true)
    {

        MessageBox.Show("This is the value of ceckhed Item " + myCheckedListBox.Items[i].ToString());

    }

}

0

埃及开发博客:在vb.net中获取CheckedListBox中选定项目的值

绑定数据后,您可以获取已选项目的值

For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
                    Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(i), DataRowView)
                    Dim XDR As DataRow = XDRV.Row
                    Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
                    Dim XValueMember As String = XDR(CheckedListBox1.ValueMember).ToString()
                    MsgBox("DisplayMember : " & XDisplayMember & "   - ValueMember : " & XValueMember )
Next

现在你可以在循环中使用 CheckedListBox 中选定项的值或显示,通过变量 XDisplayMember 和 XValueMember。希望有用。

0
我已经在这篇文章中发布了GetItemValue扩展方法,链接为通过索引获取列表框项目的值。该扩展方法适用于所有ListControl类,包括CheckedListBoxListBoxComboBox

现有的答案都不够通用,但是这个问题有一个通用解决方案。

在所有情况下,无论数据源的类型如何,都应该根据 ValueMember 计算项的基础值。

CheckedListBox 的数据源可以是 DataTable,也可以是包含对象(如 List<T>)的列表,因此 CheckedListBox 控件的项可以是 DataRowView、复杂对象、匿名类型、主类型和其他类型。

GetItemValue 扩展方法

我们需要一个类似于 GetItemTextGetItemValue 方法,但是它返回一个对象,即项的基础值,而不管您添加的项的对象类型如何。

我们可以创建一个名为GetItemValue扩展方法,用于获取项值,其工作方式类似于GetItemText
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}

使用上述方法,您无需担心ListBox的设置,它将返回所选项的预期Value。它适用于List<T>ArrayArrayListDataTable、匿名类型列表、基本类型列表以及所有其他可用作数据源的列表。以下是一个使用示例:

//Gets underlying value at index 2 based on settings
this.checkedListBox.GetItemValue(this.checkedListBox.Items[2]);

由于我们将GetItemValue方法创建为扩展方法,因此当您想要使用该方法时,请不要忘记包含放置类的命名空间。

此方法也适用于ComboBoxCheckedListBox


-1

尝试:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }

你应该添加一些代码的描述。你的代码中也缺少分号。 - Hanlet Escaño

-2
你可以尝试这个:
string s = "";

foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
    s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');

欢迎来到SO,Madhuchhanda。你的答案在实质上与已经提供的其他答案有何不同?最好不要提供重复的答案,因为这只会增加噪音,让寻求帮助的人更加困惑。 - Kirk Woll

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接