Best way to get selected item OR entered text from combobox

柔情痞子 提交于 2020-01-02 08:54:27

问题


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;

回答1:


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;



回答2:


comboBox_Code1.SelectedItem == null ? comboBox_Code1.Text : comboBox_Code1.SelectedItem.ToString()

code tested and it works ;-)




回答3:


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());


来源:https://stackoverflow.com/questions/33108261/best-way-to-get-selected-item-or-entered-text-from-combobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!