Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I'm wondering, what is better solution and why?
I suppose that the second one, as exception should be in the code just to handle errors and this is not an error (just the value is not in combo box)? Am I right? And is it the only reason? Or there's nothing wrong about both solutions?
Or is there another solution? Better than these two?

C#
try
{
   cbOwner.SelectedValue = whatever.toString();
}
catch (Exception ex)
{
   //nothing happened, program can continue
}

or
SQL
if (cbOwner.Items.FindByValue(whatever.toString()) != null)
   cbOwner.SelectedValue = whatever.toString();
Posted

What you show is a really bad way, because you may easily make a mistake with a string. Therefore, it's much better to set selected index (exact answer depends on exact type of ComboBox; there are different types under this name).

But really robust and reliable approach is to put items of some semantic data type in the list. I explain it in my past answers collected here:
combobox.selectedvalue shows {} in winform[^].

—SA
 
Share this answer
 
There was a similar problem discussed and many people provided solutions in the asp.net forum: C# How To Assign Combo Box Values / Text[^]
 
Share this answer
 
v2
Comments
Petra Cerna 7-Feb-13 9:59am    
I'm not trying to assign a value, what I'm trying to do is - if whatever.toString() exist in combo box, than select it, else just continue
shiny13 7-Feb-13 10:07am    
Well you can do all that then in an if statement. I understand our logic but I wonder why would you need to do this.

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