简体   繁体   English

如何设置comboBox的默认值?

[英]how to set default value for comboBox?

Hey i am making a comboBox that is holding a list of all the fonts name on my system, however at the beginning it does not hold any value and user needs to click on it to open it and select an item from the list. 嘿,我正在制作一个comboBox,其中包含我系统上所有字体名称的列表,但是在开始时它不包含任何值,用户需要单击它以将其打开并从列表中选择一个项目。 my question is how to set the default value for my comboBox (for example 'Arial') in case if nothing has been selected by the user and not to give error. 我的问题是如何在用户未选择任何内容的情况下为我的comboBox设置默认值(例如“ Arial”),并且不给出错误。

        foreach (FontFamily fnt in fonts.Families)
        {

            comboBox1.Items.Add(fnt.Name);

        }

You could search for a value such as "Arial" using FindString : 您可以使用FindString搜索诸如“ Arial”之类的值:

if (comboBox1.SelectedIndex == -1)
    comboBox1.SelectedIndex = comboBox1.FindString("Arial");

If you've got multiple entries starting with "Arial", the above will return the first match starting with Arial, so you may need to search for the exact string: 如果您有多个以“ Arial”开头的条目,则上面的代码将返回以Arial 开头的第一个匹配项,因此您可能需要搜索确切的字符串:

if (comboBox1.SelectedIndex == -1)
    comboBox1.SelectedIndex = comboBox1.FindStringExact("Arial Rounded MT");

You can just do: 您可以这样做:

comboBox1.SelectedValue = "Arial";

(assuming there is an element with value = Arial) (假设有一个值= Arial的元素)

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

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