我有一个字符串“test1”,我的组合框包含test1、test2和test3。如何设置选中项为“test1”?也就是说,我如何匹配我的字符串到一个组合框项目?

我想的是下面这行,但这不行。

comboBox1.SelectedText = "test1"; 

当前回答

假设test1、test2、test3属于comboBox1集合,下面的语句将工作。

comboBox1.SelectedIndex = 0; 

其他回答

应该可以

Yourcomboboxname.setselecteditem("yourstring");

如果你想设置数据库字符串,使用这个

Comboboxname.setselecteditem(ps.get string("databasestring"));

对我来说,这只管用:

foreach (ComboBoxItem cbi in someComboBox.Items)
{
    if (cbi.Content as String == "sometextIntheComboBox")
    {
        someComboBox.SelectedItem = cbi;
        break;
    }
}

MOD:如果你有你自己的对象作为项目设置在组合框,然后替换ComboBoxItem与他们中的一个:

foreach (Debitor d in debitorCombo.Items)
{
    if (d.Name == "Chuck Norris")
    {
        debitorCombo.SelectedItem = d;
        break;
    }
}

你可以说comboBox1。[0].ToString();

如果组合框中的项目是字符串,您可以尝试:

comboBox1.SelectedItem = "test1";

在组合框中枚举ListItems 获得相等的列表索引集组合框 将listindex设置为找到的值。

但如果我作为代码评审员看到这样的代码,我会建议重新考虑所有的方法算法。