Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C#
if ((Convert.ToInt16(txtID.Text) == 1 && cboCategoria.SelectedItem== "Alimentos") || Convert.ToInt16(txtID.Text)== 6 && cboCategoria.SelectedItem == "Alimentos"))
Posted
Updated 11-Apr-14 3:50am
v2
Comments
Sergey Alexandrovich Kryukov 11-Apr-14 10:02am    
No, it's not okay... :-)
—SA

The SelectedItem is an object, the whole item, you really want the SelectedText property or the SelectedValue property. So use comboBox.SelectedText instead.

http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem(v=vs.110).aspx[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 11-Apr-14 10:28am    
Correct, my 5, but I think you understand the root problem is much deeper; it's just harder to explain. Please see Solution 2.
—SA
I would add to the correct Solution 1: this is a bad style of programming; the whole idea of comparison of something in the UI state with some immediate constants in your code is bad idea and wrong code design.

Such immediate constants as "Alimentos" are referred to as "magic strings". Such programming is not maintainable, which becomes especially obvious if you write the same constant twice. The compiler won't detect any problem is you misspell any of those strings. This is a well-known anti-pattern. Please see: http://en.wikipedia.org/wiki/Magic_string_%28programming%29#Magic_strings_in_code[^].

See also: http://en.wikipedia.org/wiki/Anti-pattern[^].

What to do? In worst case, at least declare an explicit constant and do it only once in your whole solution. It should be the only place where the string is declared. These are the fundamental principles:
http://en.wikipedia.org/wiki/Single_Point_of_Truth[^],
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself[^].

But even you do it, this approach looks way too much ad-hoc. Right approach would be something like this. Don't put strings in your list boxes, combo boxes and other item controls. Create special types (classes or structures) representing the data you need for your functionality, and add instances of them to your item controls. Then, for example, for comparison, type-cast the items to your types and use your item type's members.

The remaining problem is: what is to be shown in the UI? Simple: in simplest case, whatever its method ToString() shows, so you can override System.Object.ToString(). Or, better, use binding, which is a whole big separate topic.

—SA
 
Share this answer
 
Comments
ZurdoDev 11-Apr-14 10:29am    
Good addition. +5
Sergey Alexandrovich Kryukov 11-Apr-14 10:36am    
Thank you, Ryan.
(How could you be so fast? :-)
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900