webworm
webworm

Reputation: 11019

ComboBox Items values are switched

I have a ComboBox on a Winform app that contains a list of regular expressions that match date formats. I load the ComboBox using a Dictionary so I can display an example of a matching pattern and have the actual regular expression as the SelectedValue.

  Dictionary<string, string> datePatternsSource = new Dictionary<string, string>();

  datePatternsSource.Add(@"dd-MMM-yy (05-SEP-15)", @"((\d{2})(\-)(\w{3})(\-)(\d{2}))");
  datePatternsSource.Add(@"yyyy-MM-dd (2015-09-05)", @"((\d{4})(\-)(\d{2})(\-)(\d{2}))");
  datePatternsSource.Add(@"MM/dd/yyyy (09/05/2015)", @"((\d{2})(\/)(\d{2})(\/)(\d{4}))");
  datePatternsSource.Add(@"M/d/yyyy (9/5/2015)", @"((\d{1,2})(\/)(\d{1,2})(\/)(\d{4}))");
  datePatternsSource.Add(@"yyyy/MM/dd (2015/09/05)", @"((\d{4})(\/)(\d{2})(\/)(\d{2}))");

  cboDatePatterns.DisplayMember = "Key";
  cboDatePatterns.ValueMember = "Value";
  cboDatePatterns.DataSource = new BindingSource(datePatternsSource, null);

The problem is that two of the regular expressions are not matching to the proper example. To demonstrate I call the MessageBox.Show() method to display the combobox properties.

MessageBox.Show("SelectedItem = " + cboDatePatterns.SelectedItem.ToString() + "\nSelectedValue = " + cboDatePatterns.SelectedValue.ToString());

The comboBox Correct match Incorrect match

How could these values be switched? Three out of the five items are matched correctly. Two of them are switched.

Upvotes: 1

Views: 65

Answers (1)

Jauch
Jauch

Reputation: 1518

After looking here: https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.sorted%28v=vs.110%29.aspx, I found that if you set the Sorted to true on a databound combobox on designtime, you have this behavior, while if you set it during runtime, after the databound was set, you raise an argument exception. So, the Sorted must not be used with databound combobox...

If you want the values to be sorted, you have to sort them through the Dictionary.

Or, probably best, like pointed by @Andy, Using a SortedDictionary. I tested and it worked, of course. Thanks @Andy. :)

Upvotes: 2

Related Questions