c# - Validating if a combobox it's SelectedText property is empty always fails -
simple problem: checking see if combobox has had item selected string.isnullorempty(). problem is, if is selected, error message appears. doing wrong?
here code:
private void button1click(object sender, eventargs e) { if (string.isnullorempty(combobox1.selectedtext))//here should skip else - doesn't { messagebox.show("you must select conversion type", "error"); } else { if (combobox1.selectedtext == "currency") { double input = convert.todouble(textbox1.text); if (!string.isnullorempty(combobox2.selectedtext)) { string type = combobox2.selectedtext; double result = convertcurrency(type, input); if (result != -1) { label1.text = convert.tostring(result); } } else { messagebox.show("you must select conversion type", "error"); } } else { messagebox.show("curency"); } } } note: second ever c# program - please don't yell @ me if i'm being stupid.
generally few observations/suggestions.
first you're using string values , basing logic on these values, might want using enum , binding it's values combo box. use selecteditem property , compare enum.
when nothing selected selecteditem return null, option using selectedindex return -1 when no item has been selected.
so selectedindex become like;
if (combobox1.selectedindex == -1)//nothing selected { messagebox.show("you must select conversion type", "error"); } else { //do magic } generally using string comparisons should done when "strong" int comparison or better enum comparison not possible. (maybe it's me though strings change , scary sort of stuff.)
for enum suggestion possibly @ 1 of these links;
binding enum winforms combo box, , setting it
load values of enum type combobox
is possible load items enum combobox in .net 3.5?
i'm not sure .net version , things you're using binding alot easier in wpf in old windows form (in opinion).
Comments
Post a Comment