Click here to Skip to main content
11,496,146 members (583 online)
The site is currently in read-only mode for maintenance. Posting of new items will be available again shortly.
See more: C# combobox practices
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?

try
{
   cbOwner.SelectedValue = whatever.toString();
}
catch (Exception ex)
{
   //nothing happened, program can continue
}
or
if (cbOwner.Items.FindByValue(whatever.toString()) != null)
   cbOwner.SelectedValue = whatever.toString();
Posted 7-Feb-13 3:59am
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
  Permalink  
There was a similar problem discussed and many people provided solutions in the asp.net forum: C# How To Assign Combo Box Values / Text[^]
  Permalink  
v2
Comments
Petra Cerna at 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 at 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)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 10,401
1 OriginalGriff 8,910
2 Sascha Lefèvre 3,899
3 Maciej Los 3,422
4 Richard Deeming 2,600


Advertise | Privacy | Mobile
Web02 | 2.8.150520.1 | Last Updated 7 Feb 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100