Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to check that listbox's specific item have a value or not i am doing this two if conditions but both are use less how to do this

C#
if (!String.IsNullOrEmpty(lbTaxRate.GetItemText(lbTaxRate.Items[0]))&& !String.IsNullOrEmpty(lbTaxName.GetItemText(lbTaxName.Items[0])))
                {
                    objProduct.Tax1Name = lbTaxName.GetItemText(lbTaxName.Items[0]);
                    objProduct.Tax1Rate = Convert.ToDecimal(lbTaxRate.GetItemText(lbTaxRate.Items[0]));
                }

                if (!String.IsNullOrEmpty(lbTaxRate.GetItemText(lbTaxRate.Items[1])) && !String.IsNullOrEmpty(lbTaxName.GetItemText(lbTaxName.Items[1])))
                {
                    objProduct.Tax2Name = lbTaxName.GetItemText(lbTaxName.Items[1]);
                    objProduct.Tax2Rate = Convert.ToDecimal(lbTaxRate.GetItemText(lbTaxRate.Items[1]));
                }


as you can see above item[1]..item[0]...i am checking this is not a right approch so how i can i do this
Posted
Updated 4-Jun-14 22:29pm
v2

The question is is ill-posed: a list item, it it even exist, is some object. It does exist and, hence, always has a value. It depends on what do you mean by "value", because there are value types and reference types, but, from the point of your of the ListBox, this is an object of the type System.Object, which implies that the item reference something.

Again, it depends on what do you mean by "value". Apparently, you work with strings which you interpret as integers. Then you can consider empty string as "not a value", or, more generally, if decimal.TryParse(string, out decimal) returns false, you can consider this as "not a value". Please see: http://msdn.microsoft.com/en-us/library/9zbda557%28v=vs.110%29.aspx[^].

However, the whole approach is wrong.

You should not work with strings representing data instead of data itself. ListBox elements could be of any type, and you should use this fact by storing actual data in it. This is explained in detail in my past answer: combobox.selectedvalue shows {} in winform[^].

Don't use strings representing data where you need the data itself.

—SA
 
Share this answer
 
v2
Comments
Muhamad Faizan Khan 5-Jun-14 4:29am    
question updated
I would use arrays for both objProduct.TaxName and objProduct.TaxRate (or better a single array of a 'Tax' class instances). This way I wouldn't have to duplicate the code.
 
Share this answer
 

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