4

I have a combobox that I pre-populate with numerous possible choices. But I also want the option open for the user to manually enter text that is not one of the choices. So I leave the DropDownStyle set to DropDown so this is possible.

My question is, what is the most efficient (yet proper) way to write the code to return the value the user either selects, or manually enters?

Currently I am using the following code. But it seems a bit verbose for such a simple task. Is there a better (shorter) way to obtain the same result?

        string Code1 = comboBox_Code1.GetItemText(comboBox_Code1.SelectedItem);
        if (Code1.Length == 0) Code1 = comboBox_Code1.Text;
Joe Gayetty
  • 1,521
  • 2
  • 22
  • 35
  • What's the value of SelectedIndex when the user has typed information into the field? If it's -1 you could always use that to check if your pulling a selected value or if its user-entered. – Calvin Oct 13 '15 at 16:53
  • Yes it is -1 when text is manually entered. Good idea. But I am not sure if/how I can use that for a shorter solution though. – Joe Gayetty Oct 13 '15 at 17:01
  • @jgayetty If you are using windows forms' combobox, then you can use `comboBox_Code1.Text` to get either typed/selecteditem text. – Siva Gopal Oct 13 '15 at 17:06
  • @SivaGopal Could it be that easy? I tested your solution and it seems to work. Post your suggestion as the answer and I will accept it. – Joe Gayetty Oct 13 '15 at 17:53
  • @jgayetty If it works perfectly with less effort, it should be easy :) – Siva Gopal Oct 13 '15 at 17:56

3 Answers3

7

Siva Gopal posted the answer in a comment. It is by far the shortest and simplest solution suggested. I have tested it and it works when the user selects a pre-populated value, and it also works when the user manually types in a value!

string Code1 = comboBox_Code1.Text;
Joe Gayetty
  • 1,521
  • 2
  • 22
  • 35
0
comboBox_Code1.SelectedItem == null ? comboBox_Code1.Text : comboBox_Code1.SelectedItem.ToString()

code tested and it works ;-)

Blodnatt
  • 31
  • 5
  • Above code produced a System.NullReferenceException if a value was entered manually. For selected item it worked. – Joe Gayetty Oct 13 '15 at 16:58
0

You can use the SelectedIndex suggestion combined with immediate if suggestion to produce the following. I wonder what you do if the user doesn't enter a value at all. It seems like an oversight.

return (comboBox_Code1.SelectedIndex == -1 
         ? comboBox_Code1.Text 
         : comboBox_Code1.SelectedItem.ToString());
gustavodidomenico
  • 4,640
  • 1
  • 34
  • 50
MDill33
  • 21
  • 2