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

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

comboBox1.SelectedText = "test1"; 

当前回答

comboBox1.SelectedItem.Text = "test1";

其他回答

请试试这个方法,它对我很有效:

Combobox1.items[Combobox1.selectedIndex] = "replaced text";

我知道这不是执勤人员要求的,但会不会是他们不知道呢?这里已经有几个答案,所以即使这很长,我认为它可能对社区有用。

使用枚举填充组合框可以方便地使用SelectedItem方法以编程方式在组合框中选择项目,以及从组合框中加载和读取。

public enum Tests
    {
        Test1,
        Test2,
        Test3,
        None
    }

// Fill up combobox with all the items in the Tests enum
    foreach (var test in Enum.GetNames(typeof(Tests)))
    {
        cmbTests.Items.Add(test);
    }

    // Select combobox item programmatically
    cmbTests.SelectedItem = Tests.None.ToString();

如果你双击组合框,你可以处理选定的索引改变事件:

private void cmbTests_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!Enum.TryParse(cmbTests.Text, out Tests theTest))
    {
        MessageBox.Show($"Unable to convert {cmbTests.Text} to a valid member of the Tests enum");
        return;
    }

    switch (theTest)
    {
        case Tests.Test1:
            MessageBox.Show("Running Test 1");
            break;

        case Tests.Test2:
            MessageBox.Show("Running Test 2");
            break;

        case Tests.Test3:
            MessageBox.Show("Running Test 3");
            break;

        case Tests.None:

            // Do nothing

            break;

        default:
            MessageBox.Show($"No support for test {theTest}.  Please add");
            return;
    }
}

然后可以从按钮单击处理程序事件运行测试:

 private void btnRunTest1_Click(object sender, EventArgs e)
    {
        cmbTests.SelectedItem = Tests.Test1.ToString();
    }

如果你通过数据集绑定数据源,那么你应该使用"SelectedValue"

cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];

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

comboBox1.SelectedIndex = 0; 

这个方案是基于MSDN的,我做了一些修改。

It finds exact or PART of string and sets it. private int lastMatch = 0; private void textBoxSearch_TextChanged(object sender, EventArgs e) { // Set our intial index variable to -1. int x = 0; string match = textBoxSearch.Text; // If the search string is empty set to begining of textBox if (textBoxSearch.Text.Length != 0) { bool found = true; while (found) { if (comboBoxSelect.Items.Count == x) { comboBoxSelect.SelectedIndex = lastMatch; found = false; } else { comboBoxSelect.SelectedIndex = x; match = comboBoxSelect.SelectedValue.ToString(); if (match.Contains(textBoxSearch.Text)) { lastMatch = x; found = false; } x++; } } } else comboBoxSelect.SelectedIndex = 0; }

希望我能帮上忙!