How to show text in combobox when no item selected?

前端 未结 16 1343
太阳男子
太阳男子 2020-11-30 06:39

C# & .Net 2.0 question (WinForms)

I have set of items in ComboBox and non of them selected. I would like to show a string on combo \"Pl

16条回答
  •  攒了一身酷
    2020-11-30 07:01

    I was hoping to find a solution to this as well. I see that this is an older post, but hoping my approach might simplify this problem for someone else.

    I was using a combobox with a drop down style of DropDownList, but this should work with other styles. In my case I wanted the text to read "Select Source" and I wanted the other options to be "File" and "Folder"

    comboBox1.Items.AddRange(new string[] {"Select Source", "File", "Folder" });
    comboBox1.Text = "Select Source";
    

    You can select the 0 index instead if you like. I then removed the "Select Source" item when the index is changed as it no longer matters if that text is visible.

    comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_IndexChanged);
    
    private void comboBox1_IndexChanged(object sender, EventArgs e)
        {
            comboBox1.Items.Remove("Select Source");
            if (comboBox1.SelectedIndex != -1)
            {
                if (comboBox1.SelectedIndex == 0) // File
                {
                    // Do things
                }
                else if (comboBox1.SelectedIndex == 1) // Folder
                {
                    // Do things
                }
            }
        }
    

    Thanks

提交回复
热议问题