Click here to Skip to main content
13,143,774 members (29,178 online)
Rate this:
Please Sign up or sign in to 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?

   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 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.170915.1 | Last Updated 7 Feb 2013
Copyright © CodeProject, 1999-2017
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