title: ComboBox.SelectedValue is not Working
body: <p>I have a WinForms application. I've populated my ComboBox with the following code:</p>
  
  <pre><code>cboGridSize.Items.Clear();
  for (int i = 2; i &lt;= 12; i++)
      cboGridSize.Items.Add(new KeyValuePair&lt;string,int&gt;(i.ToString(), i));
  cboGridSize.SelectedValue = 4;
  </code></pre>
  
  <p>However, the last line has absolutely no effect. The ComboBox appears with no items selected.</p>
  
  <p>So I was doing some debugging and noticed some odd things. The following image is from the watch window after setting <code>cboGridSize.SelectedIndex</code> to 0.</p>
  
  <p><a href="http://www.softcircuits.com/Client/debugwin.jpg">Watch Window http://www.softcircuits.com/Client/debugwin.jpg</a></p>
  
  <p>Even though the <code>SelectedItem</code> property contains exactly what I would expect, <code>SelectedValue</code> is still <code>null</code>. Although the documentation for <code>SelectedValue</code> is pathetic, I understood it would contain the value of the selected item (<code>SelectedItem</code>). Instead, the two properties seem completely unrelated. Can anyone see what I have wrong?</p>
  
  <p>As you can see, I have the <code>ValueMember</code> property set. And the <code>DropDownStyle</code> property is set to <code>DropDownList</code>.</p>
  
  <hr>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Once Nikolay Khil set me straight on the issue here (why the docs for <code>SelectedValue</code> don't do that escapes me), I decided to simply write my own code to accomplish the same task. I'm posting it here in case anyone is interested.</p>
  
  <pre><code>static class ComboBoxHelper
  {
      public static void LookupAndSetValue(this ComboBox combobox, object value)
      {
          if (combobox.Items.Count &gt; 0)
          {
              for (int i = 0; i &lt; combobox.Items.Count; i++)
              {
                  object item = combobox.Items[i];
                  object thisValue = item.GetType().GetProperty(combobox.ValueMember).GetValue(item);
                  if (thisValue != null &amp;&amp; thisValue.Equals(value))
                  {
                      combobox.SelectedIndex = i;
                      return;
                  }
              }
              // Select first item if requested item was not found
              combobox.SelectedIndex = 0;
          }
      }
  }
  </code></pre>
  
  <p>This is implemented as an extension method so I simply change my original code as follows:</p>
  
  <pre><code>cboGridSize.Items.Clear();
  for (int i = 2; i &lt;= 12; i++)
      cboGridSize.Items.Add(new KeyValuePair&lt;string,int&gt;(i.ToString(), i));
  cboGridSize.LookupAndSetValue(4);
  </code></pre>