Click here to Skip to main content
11,798,866 members (74,035 online)
Rate this: bad
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?

   cbOwner.SelectedValue = whatever.toString();
catch (Exception ex)
   //nothing happened, program can continue
if (cbOwner.Items.FindByValue(whatever.toString()) != null)
   cbOwner.SelectedValue = whatever.toString();
Posted 7-Feb-13 2:59am
Rate this: bad
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[^].

Rate this: bad
Please Sign up or sign in to vote.

Solution 2

There was a similar problem discussed and many people provided solutions in the forum: C# How To Assign Combo Box Values / Text[^]
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 CPallini 505
1 OriginalGriff 503
2 Richard MacCutchan 321
3 Maciej Los 245
4 phil.o 244
0 OriginalGriff 2,270
1 Maciej Los 1,810
2 KrunalRohit 1,496
3 CPallini 1,425
4 Richard MacCutchan 1,109

Advertise | Privacy | Mobile
Web04 | 2.8.151002.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