2009/08/27

[Winform] Set ComboBox's value by the given value

Here is the same purpose of the DropDownList control. Here is the same thing for the winform ComboBox control.
internal static void SetDropDownByText(ComboBox cbox, string text)
{
  if (cbox != null)
  {
    DataTable dt = (DataTable)cbox.DataSource;
    for (int i = 0; i < dt.Rows.Count; i++)
    {
      if ((string)dt.Rows[i][cbox.DisplayMember] == text)
      {
        cbox.SelectedIndex = i;
        break;
      }
    }
  }
}

internal static void SetDropDownByValue(ComboBox cbox, string text)
{
  if (cbox != null)
  {
    DataTable dt = (DataTable)cbox.DataSource;
    for (int i = 0; i < dt.Rows.Count; i++)
    {
      if ((string)dt.Rows[i][cbox.ValueMember] == text)
      {
        cbox.SelectedIndex = i;
        break;
      }
    }
  }
}
How to use:
SetDropDownByText(cboxCustomer, "Kenny");
SetDropDownByValue(cboxCustomer, "VIP0001");

There must be a easier way to do the same thing. Let me know if you have one.

No comments:

Post a Comment