【问题标题】:CheckedListBox - Search for an item by textCheckedListBox - 按文本搜索项目
【发布时间】:2012-02-02 09:12:22
【问题描述】:

我有一个CheckedListBox 绑定到一个DataTable。现在我需要以编程方式检查一些项目,但我发现SetItemChecked(...) 方法只接受项目索引。

有没有一种实用的方法可以在不知道项目索引的情况下通过文本/标签获取项目?

(注意:我对 WinForms 的经验有限...)

【问题讨论】:

    标签: c# .net winforms checkedlistbox


    【解决方案1】:

    你可以实现自己的SetItemChecked(string item);

        private void SetItemChecked(string item)
        {
            int index = GetItemIndex(item);
    
            if (index < 0) return;
    
            myCheckedListBox.SetItemChecked(index, true);
        }
    
        private int GetItemIndex(string item)
        {
            int index = 0;
    
            foreach (object o in myCheckedListBox.Items)
            {
                if (item == o.ToString())
                {
                    return index;
                }
    
                index++;
            }
    
            return -1;
        }
    

    checkListBox 使用object.ToString() 显示列表中的项目。您可以实现一个搜索所有对象的方法。ToString() 以获取项目索引。获得项目索引后,您可以调用SetItemChecked(int, bool);

    希望对你有帮助。

    【讨论】:

    • 也许它取决于与DataTable的绑定,但在我的情况下o.ToString()返回"System.Data.DataRowView",所以我认为我必须使用myCheckedListBox.GetItemText(o)...
    • 当我看到“实用方法”时,我的意思是现有的方法来做到这一点......但似乎框架提供了类似的东西,所以我将实现我自己的方法,就像你一样建议。非常感谢。
    • 非常感谢这种方法 - 我见过的大多数东西都相当肮脏或太琐碎。出于我的目的,我正在加载 XML 并使用自定义对象根据设置填充选中的项目。
    【解决方案2】:

    您可以尝试浏览您的数据表。您可以对 DataTabke.Rows 属性执行 foreach 或使用 SQL 语法,如下所示:

    DataTable dtTable = ...
    DataRow[] drMatchingItems = dtTable.Select("label = 'plop' OR label like '%ploup%'"); // I assumed there is a "label" column in your table
    int itemPos = drMatchingItems[0][id]; // take first item, TODO: do some checking of the length/matching rows
    

    干杯,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多