【问题标题】:WinForms - ComboBox: Find selected item and set indexWinForms - ComboBox:查找所选项目并设置索引
【发布时间】:2011-11-17 22:07:34
【问题描述】:

我有一个 RadMultiColumnComboBox 类型的 ComboBox 控件,我正在尝试搜索并找到一个字符串,然后以编程方式设置选定的索引。

这是我的代码:

        // get reference to drop down:
        RadMultiColumnComboBox myComboBox = this.BaseFieldControl;

        // find and set: 
        string toFind = "SomeValue";
        myComboBox.SelectedIndex = myComboBox .FindExact( toFind );

问题在于,无论我将什么字符串传递给 FindExact,控件的 FindExact 方法都会返回 -1。

当应用程序运行时,我使用即时窗口来测试并输入各种字符串;无论我使用什么字符串,它都会返回 -1。

如果我检查 myComboBox,DataSource 属性中有 10 个项目。

这是 ComboBox 的表示 - 它可能会有所帮助:

【问题讨论】:

    标签: c# winforms combobox telerik


    【解决方案1】:

    您可以将数据源转换为原始类型并从数据源中查找索引:

    var data=(List<YourType)myComboBox.DataSource;
    myComboBox.SelectedIndex=data.FindIndex(p=>p.Text=="SomeValue");
    

    【讨论】:

    • p.Text 是一个示例,您必须将其替换为 p.(您的文件要搜索)=="SomeData"
    • 我收到一个异常:{“无法转换类型为'System.ComponentModel.BindingList1[ECS.Common.Entities.MyType]' to type 'System.Collections.Generic.List1[ECS.Common.Entities.MyType]'的对象。”}
    • 我想我需要转换为 List
    • ps 这是我更新的代码示例: var data = (List)myComboBox.DataSource; myComboBox.SelectedIndex = data.FindIndex(p => p.DisplayValue == "SomeValue");
    • 如果您在第 1 行中使用数据绑定源,请替换为:var data=(List
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    相关资源
    最近更新 更多