【问题标题】:How to set ComboBox index?如何设置组合框索引?
【发布时间】:2018-09-14 19:37:06
【问题描述】:

“我知道问题标题可能会重复,但没有找到我正在寻找的解决方案。”

一个组合框,其中包含大约 50 个控件,组合为文本框和组合框。我必须为它们设置值,并且不想写 50 行来为每个控件设置值,所以我想出了下面的代码。但这在组合框的情况下不起作用。或者,如果你们能提出更好的建议,那就太好了。

if(controlsInGroupBox == editStep.Count)
{
    int i = 0;
    foreach (Control ctr in universalGroupBoxObject.Controls)
    {  
        if (ctr is TextBox)
        {
            ctr.Text = editStep[i];
        }
        if (ctr is ComboBox)
        {
            //ctr.SelectedIndex = cntrlObjListMain.comboBoxLocation.FindStringExact(editStep[i]);
           //ctr.SelectedIndex is not working
         }
        i++;
    }
}

【问题讨论】:

  • var combo = (ComboBox)ctr; 然后combo.SelectedIndex = ...
  • @RezaAghaei 非常感谢它对我有用。

标签: c# winforms combobox


【解决方案1】:

如果您将数据绑定到组合框,则默认情况下会选择第一项,而无需选择一项。

例如

List<string> items = new List<string>() { "aa", "bb", "cc", "dd" };

combobox1.DataSource = items;

只要列表中有项目,SelectedIndex 就应该可以工作。

ctr.SelectedIndex = ctr.Items.Count > 0 ? 0 : -1;

如果有项目,上面会选择一个项目,否则不会选择任何项目。

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    相关资源
    最近更新 更多