如何使用C#将comboBox中选定的项目设置为与我的字符串匹配?

236

我有一个字符串 "test1",我的组合框包含 test1test2test3。如何将选定的项目设置为 "test1"?也就是说,如何将我的字符串与组合框中的一个项目匹配?

我想到了下面这行代码,但它不起作用。

comboBox1.SelectedText = "test1"; 

它为什么不工作?当这行代码运行时会发生什么? - Kate Gregory
@KateGregory 它只是将“test1”字符串连接到现有文本中。 - solujic
如果您知道该项的值,可以使用以下方法:comboBox1.SelectedValue = 您的字符串的值; - César León
SelectedText 将“选定”的文本更改为 test1。如果没有进行“选择”(标记的文本),则文本将插入插入符号位置。 - AaA
27个回答

1

在ComboBox没有父级之前,所有设置ComboBox项目的方法、技巧和代码行都不起作用。


1
combo.Items.FindByValue("1").Selected = true;

3
如果找不到“1”,这也会导致异常。 - Gary

1
我创建了一个函数,它将返回该值的索引。
        public static int SelectByValue(ComboBox comboBox, string value)
        {
            int i = 0;
            for (i = 0; i <= comboBox.Items.Count - 1; i++)
            {
                DataRowView cb;
                cb = (DataRowView)comboBox.Items[i];
                if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
                {
                    return i;
                }
            }
            return -1;
        }

1

我知道这不是原帖所问的,但是他们可能不知道吗?虽然这篇文章有点长,但是考虑到对社区有用,我认为它还是值得的。

使用枚举来填充组合框可以轻松地使用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();
    }

-1
您可以这样说:comboBox1.Text = comboBox1.Items[0].ToString();

-2
请尝试这种方式,它对我有效:
Combobox1.items[Combobox1.selectedIndex] = "replaced text";

你应该首先检查selectedIndex不是-1,或者更准确地说,它应该是>= 0且<.items.length。 - Gary

-3

它应该能工作。

Yourcomboboxname.setselecteditem("yourstring");

如果您想设置数据库字符串,请使用以下内容

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接