简体   繁体   English

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

[英]How to get value of checked item from CheckedListBox?

I have used a CheckedListBox over my WinForm in C#.我在 C# 中的 WinForm 上使用了 CheckedListBox。 I have bounded this control as shown below -我已经限制了这个控件,如下所示 -

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

I can get the indices of checked items, but how can i get checked item text and value.我可以获得已检查项目的索引,但是如何获得已检查项目的文本和值。 Rather how can i enumerate through CheckedItems accessing Text and Value?而是如何通过 CheckedItems 枚举访问文本和值?

Thanks for sharing your time.感谢您分享您的时间。

Cast it back to its original type, which will be a DataRowView if you're binding a table, and you can then get the Id and Text from the appropriate columns:将它转换回它的原始类型,如果你绑定一个表,它将是一个 DataRowView,然后你可以从相应的列中获取 Id 和 Text:

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

EDIT: I realized a little late that it was bound to a DataTable.编辑:我意识到它绑定到数据表有点晚了。 In that case the idea is the same, and you can cast to a DataRowView then take its Row property to get a DataRow if you want to work with that class.在这种情况下,想法是相同的,如果您想使用该类,您可以将其转换为DataRowView然后使用其Row属性来获取DataRow

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

You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:您需要将项目转换或解析为它们的强类型等效项,或者使用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);
}

You need to cast the item to access the properties of your class.您需要强制转换该项目以访问您的类的属性。

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

Alternately, you could use the OfType extension method to get strongly typed results back without explicitly casting within the loop:或者,您可以使用OfType扩展方法来获取强类型结果,而无需在循环内显式转换:

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

You can iterate over the CheckedItems property:您可以遍历CheckedItems属性:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
    MyCompanyClass company = (MyCompanyClass)itemChecked;    
    MessageBox.Show("ID: \"" + company.ID.ToString());
}

http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx

To get the all selected Items in a CheckedListBox try this:要获取 CheckedListBox 中的所有选定项目,请尝试以下操作:

In this case ths value is a String but it's run with other type of Object:在这种情况下,ths 值是一个字符串,但它与其他类型的对象一起运行:

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

    }

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

I've already posted GetItemValue extension method in this post Get the value for a listbox item by index .我已经在这篇文章中发布了GetItemValue扩展方法Get the value for a listbox item by index This extension method will work for all ListControl classes including CheckedListBox , ListBox and ComboBox .此扩展方法适用于所有ListControl类,包括CheckedListBoxListBoxComboBox


None of the existing answers are general enough, but there is a general solution for the problem.现有的答案都不够通用,但该问题有一个通用的解决方案。

In all cases, the underlying Value of an item should be calculated regarding to ValueMember , regardless of the type of data source.在所有情况下,无论数据源的类型如何,都应根据ValueMember计算项目的基础Value

The data source of the CheckedListBox may be a DataTable or it may be a list which contains objects, like a List<T> , so the items of a CheckedListBox control may be DataRowView , Complex Objects, Anonymous types, primary types and other types. CheckedListBox的数据源可能是一个DataTable也可能是一个包含对象的List<T> ,如List<T> ,因此CheckedListBox控件的项可能是DataRowView 、复杂对象、匿名类型、主要类型和其他类型。

GetItemValue Extension Method GetItemValue 扩展方法

We need a GetItemValue which works similar to GetItemText , but return an object, the underlying value of an item, regardless of the type of object you added as item.我们需要一个GetItemValue ,它的工作原理类似于GetItemText ,但返回一个对象,即项目的基础值,而不管您添加为项目的对象类型如何。

We can create GetItemValue extension method to get item value which works like GetItemText :我们可以创建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);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item.使用上述方法,您无需担心ListBox设置,它将返回项目的预期Value It works with List<T> , Array , ArrayList , DataTable , List of Anonymous Types, list of primary types and all other lists which you can use as data source.它适用于List<T>ArrayArrayListDataTable 、匿名类型列表、主要类型列表以及您可以用作数据源的所有其他列表。 Here is an example of usage:下面是一个使用示例:

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

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace in which you put the class.由于我们创建了GetItemValue方法作为扩展方法,因此当您要使用该方法时,不要忘记包含放置类的命名空间。

This method is applicable on ComboBox and CheckedListBox too.此方法也适用于ComboBoxCheckedListBox

Egypt Development Blog : Get value of checked item in CheckedListBox in vb.net 埃及开发博客:在 vb.net 中获取 CheckedListBox 中选中项的值

after bind CheckedListBox with data you can get value of checked items使用数据绑定 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

now you can use the value or Display of checked items in CheckedListBox from the 2 variable XDisplayMember And XValueMember in the loop现在您可以使用循环中 2 个变量 XDisplayMember 和 XValueMember 中 CheckedListBox 中选中项的值或显示

hope to be useful.希望有用。

try:尝试:

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

You may try this :你可以试试这个:

string s = "";

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM