简体   繁体   English

如何使用 C# 设置 comboBox 中的所选项目以匹配我的字符串?

[英]How do I set the selected item in a comboBox to match my string using C#?

I have a string "test1" and my comboBox contains test1 , test2 , and test3 .我有一个字符串“test1”,我的 comboBox 包含test1test2test3 How do I set the selected item to "test1"?如何将所选项目设置为“test1”? That is, how do I match my string to one of the comboBox items?也就是说,如何将我的字符串与 comboBox 项之一匹配?

I was thinking of the line below, but this doesn't work.我正在考虑下面的行,但这行不通。

comboBox1.SelectedText = "test1"; 

这应该可以解决问题:

Combox1.SelectedIndex = Combox1.FindStringExact("test1")

Have you tried the Text property?您是否尝试过Text属性? It works for me.这个对我有用。

ComboBox1.Text = "test1";

The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box. SelectedText 属性用于组合框文本框部分中可编辑文本的选定部分。

Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.假设您的组合框不是数据绑定的,您需要在表单的“items”集合中找到对象的索引,然后将“selectedindex”属性设置为适当的索引。

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.请记住,如果未找到该项目,IndexOf 函数可能会抛出参数异常。

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

comboBox1.SelectedItem = "test1";

For me this worked only:对我来说,这只有效:

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

MOD: and if You have your own objects as items set up in the combobox, then substitute the ComboBoxItem with one of them like: MOD:如果您有自己的对象作为组合框中设置的项目,则将 ComboBoxItem 替换为其中之一,例如:

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

在 Windows 窗体中试试这个。

SelectedText is to get or set the actual text in the string editor for the selected item in the combobox as documented here . SelectedText是获取或设置字符串编辑所选项目的实际文本在下拉列表作为记录在这里 This goes uneditable if you set:如果您设置,这将不可编辑:

comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Use:采用:

comboBox1.SelectedItem = "test1";

or:要么:

comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");

I've used an extension method:我使用了一种扩展方法:

public static void SelectItemByValue(this ComboBox cbo, string value)
{
    for(int i=0; i < cbo.Items.Count; i++)
    {
        var prop = cbo.Items[i].GetType().GetProperty(cbo.ValueMember);
        if (prop!=null && prop.GetValue(cbo.Items[i], null).ToString() == value)
        {
             cbo.SelectedIndex = i;
             break;
        }
    } 
}

Then just consume the method:然后只需使用该方法:

ddl.SelectItemByValue(value);
comboBox1.SelectedItem.Text = "test1";

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

comboBox1.SelectedIndex = 0; 

I've filled my ComboBox with een DataTable filled from a database.我已经用从数据库中填充的 een DataTable 填充了我的 ComboBox。 Then I've set the DisplayMember and the ValueMember.然后我设置了 DisplayMember 和 ValueMember。 And I use this code to set the selected item.我使用此代码来设置所选项目。

foreach (DataRowView Row in ComboBox1.Items)
{
    if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}

This solution is based on MSDN with some modifications I made.该解决方案基于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; }

I hope I helped!我希望我有所帮助!

我使用KeyValuePair进行 ComboBox 数据绑定,我想按查找项目,因此这在我的情况下有效:

comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");
  • Enumerate ListItems in combobox枚举组合框中的列表项
  • Get equal ones listindex set combobox获取相等的列表索引集组合框
  • Set listindex to the found one.将 listindex 设置为找到的一个。

But if I see such a code as a code reviewer, I would recommend to reconsider all the method algorithm.但是如果我作为代码审查者看到这样的代码,我会建议重新考虑所有方法算法。

You don't have that property in the ComboBox.您在 ComboBox 中没有该属性。 You have SelectedItem or SelectedIndex.您有 SelectedItem 或 SelectedIndex。 If you have the objects you used to fill the combo box then you can use SelectedItem.如果您有用于填充组合框的对象,则可以使用 SelectedItem。

If not you can get the collection of items (property Items) and iterate that until you get the value you want and use that with the other properties.如果不是,您可以获取项目集合(属性项目)并对其进行迭代,直到获得所需的值并将其与其他属性一起使用。

hope it helps.希望能帮助到你。

_cmbTemplates.SelectedText = "test1"

或者可能

_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");

Find mySecondObject (of type MyObject) in combobox (containing a list of MyObjects) and select the item:在组合框(包含 MyObjects 列表)中找到 mySecondObject(MyObject 类型)并选择项目:

foreach (MyObject item in comboBox.Items)
{
   if (item.NameOrID == mySecondObject.NameOrID)
    {
        comboBox.SelectedItem = item;
        break;
    }
}

设置 ComboBox 项的所有方法、技巧和代码行将无法工作,直到 ComboBox 具有父项。

I have created a Function which will return the Index of the Value我创建了一个函数,它将返回值的索引

        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;
        }

这对我有用.....

comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];

I know this isn't what the OP asked but could it be that they don't know?我知道这不是 OP 所问的,但他们可能不知道吗? There are already several answers here so even though this is lengthy I thought it could be useful to the community.这里已经有几个答案,所以即使这很长,我认为它可能对社区有用。

Using an enum to fill a combo box allows for easy use of the SelectedItem method to programmatically select items in the combobox as well as loading and reading from the combobox.使用枚举填充组合框允许轻松使用 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();

If you double click the combo box you can handle the selected index changed event:如果双击组合框,您可以处理选定的索引更改事件:

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;
    }
}

You can then run tests from a button click handler event:然后,您可以从按钮单击处理程序事件运行测试:

 private void btnRunTest1_Click(object sender, EventArgs e)
    {
        cmbTests.SelectedItem = Tests.Test1.ToString();
    }
  ListItem li = DropDownList.Items.FindByValue("13001");
  DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);

For your case you can use对于您的情况,您可以使用

DropDownList.Items.FindByText("Text");

if you are binding Datasource via Dataset, then you should use "SelectedValue"如果您通过数据集绑定数据源,那么您应该使用“SelectedValue”

cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];
combo.Items.FindByValue("1").Selected = true;

你可以说comboBox1.Text = comboBox1.Items[0].ToString();

请尝试这种方式,它对我有用:

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

It should work它应该工作

Yourcomboboxname.setselecteditem("yourstring");

And if you want to set database string use this如果你想设置数据库字符串使用这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM