Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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 Mathew Soji 334
1 Maciej Los 295
2 BillWoodruff 290
3 Afzaal Ahmad Zeeshan 257
4 DamithSL 225
0 OriginalGriff 6,369
1 Sergey Alexandrovich Kryukov 5,973
2 DamithSL 5,183
3 Manas Bhardwaj 4,673
4 Maciej Los 4,045


Advertise | Privacy | Mobile
Web02 | 2.8.1411019.1 | Last Updated 7 Feb 2013
Copyright © CodeProject, 1999-2014
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