简体   繁体   中英

VS2010/C#: How do you set the default value of a ComboBox in the IDE?

I'm writing a Windows Forms app in C#, using Visual Studio 2010.

It has a combo box. I've set the DropDownStyle to "DropDownList", and added a few lines to "Items".

Q: Is there any way for me to set SelectedItemIndex in the "Properties" editor, so that line in the "Items" collection will appear as the default when the combo box appears?

I know I can programmatically set "myComboBox.SelectedItemIndex = NNN" in my Form_Load method, but I'm SURE there's probably some way to do it in the MSVS IDE, too.

Any ideas?

Thank you in advance!

I'm not sure if this is what your asking for but if you want a specific item to be set as default IE you load the form and there is already a value selected for you.

Simply put this into your public Form1() method.

comboBox1.SelectedItem = "Test1"; 
//comboBox1 change to the name of 
//your combobox
//Test1 change to the item in your list of items that you want 
//defaulted.

I think that is by far the best way to do it.

Not Sure if the exact thing can be accomplished but Visual Studio provides a way of storing the values in its Application Settings, through which you can accomplish 2 things:

  1. Set a Default value, the first time ever the Form is opened by the User (Note: Applicable only for the first time)
  2. The last selection of the user gets saved and the next time the User opens the Form, his last selection gets reflected automatically which is a quite good User experience.

Select the ComboBox and open its Properties Section, Under (Application Settings), select the (Property Binding), once the Application Settings for ComboBox opens, select the Text property and create an Application Setting. This would be the value which is selected by default the first time the user opens the Form, after that whatever Selection is made by the User, would be reflected the next time the Form is opened.

You could set the Text property of the ComboBox in the Properties window, to one of the values from your collection that you want as the default.

在此输入图像描述

However this would require the DropDownStyle to be DropDown , and make your ComboBox editable.

If that's more acceptable to you, and you still want to make it un-editable, you can override the KeyPress event for the ComboBox as follows.

    private void comboBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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