如何设置默认的组合框 [英] How to Set default combobox

查看:212
本文介绍了如何设置默认的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直在寻找设置为我的组合框的默认值。我发现了一些东西,但没有人似乎工作。

So I've been looking to set a default value for my combobox. I found a few things but none of them seem to work.

其实,如果我创建了一个简单的组合框,并使用它的作品 comboBox1.SelectedIndex = comboBox1.Items.IndexOf(东西)但一旦我动态生成组合框的内容,我无法得到它的工作了。

Actually, it works if I create a simple combobox and use comboBox1.SelectedIndex = comboBox1.Items.IndexOf("something") but once I dynamically generate the contents of the comboboxes, I can't get it to work anymore.

这是我如何填写我的组合框(位于类的构造函数);

This is how I fill my combo box (located in the class's constructor);

        string command = "SELECT category_id, name FROM CATEGORY ORDER BY name";
        List<string[]> list = database.Select(command, false);

        cbxCategory.Items.Clear();

        foreach (string[] result in list)
        {
            cbxCategory.Items.Add(new ComboBoxItem(result[1], result[0]));
        }



我似乎无法得到它的工作设置默认值,就像如果我把 cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf(新)上面的代码下面,它不会工作。

I can't seem to get it to work to set a default value, like if I place cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New") below the above code, it won't work.

的WinForms,顺便说一句。

WinForms, by the way.

感谢您提前。

推荐答案

cbxCategory.SelectedIndex 应该从 0 设置为一个整数 Items.Count-1

cbxCategory.SelectedIndex should be set to an integer from 0 to Items.Count-1 like

cbxCategory.SelectedIndex  = 2;

 cbxCategory.SelectedIndex = cbxCategory.Items.IndexOf("New") 

应该返回 - 1只要不ComboboxItem mutches字符串(新);

should return -1 as long as no ComboboxItem mutches the string ("New");

另一种解决办法,虽然我不喜欢它多少将

another solution though i don't like it much would be

foreach(object obj in cbxCategory.Items){ 
    String[2] objArray = (String[])obj ;
    if(objArray[1] == "New"){
       cbxCategory.SelectedItem = obj;
       break; 
    }
}



这也许还需要以下改造你的代码

perhaps this also requires the following transformation to your code

    foreach (string[] result in list)
    {
      cbxCategory.Items.Add(result);
    }



我没有测试的代码,我不知道对铸件字符串[2],但类似的事情应该工作

I haven't tested the code and i am not sure about the casting to String[2] but something similar should work

这篇关于如何设置默认的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆