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

前端 未结 3 794
别那么骄傲
别那么骄傲 2021-02-20 07:49

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\

相关标签:
3条回答
  • 2021-02-20 08:15

    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.

    0 讨论(0)
  • 2021-02-20 08:19

    I'm not sure if this is what your asking for but if you want a specific item to be set as default I.E 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.

    0 讨论(0)
  • 2021-02-20 08:26

    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;
        }
    
    0 讨论(0)
提交回复
热议问题