Register
Thursday, September 09, 2010
 
 DBAs And ProgrammersBlog
  
News! Minimize
   
 
 Print   
 
Misc Blog Stuff Minimize
   
 
 Print   
 
The Reluctant DBA Minimize
 
 
 
 Print   
 
Reluctant DBA Minimize
   
 
  
 
Reluctant DBA Minimize
   
 
  
 
The Reluctant DBA Minimize
 
Nov6

Written by:CarpDeus
11/6/2008 9:30 AM 

It's an old problem. Let's say you want to use a ComboBox in your WinForm application and you want to have a display and a value that are separate. If you are using DataBind that's a breeze, just specify the two columns separately. But ComboBox.Items.Add() only takes an object. So, if you want to add a string to display and use that string as the value, you're all set. If you want something more then you need to create a ComboBox item object. Which isn't supplied by default. So you create one. The only good news for 2008 is that it cuts the number of lines by 2/3 because of the automagic properties syntax. Here's the class you'll need:

/// <summary>
/// cbItem is a handy class for adding items to
/// a ComboBox when you don't want to databind.
/// </summary>
public class cbItem
{
  /// <summary>
  /// The name of the object
  /// </summary>
  public string Name { get; set; }

  /// <summary>
  /// The value of the object
  /// </summary>
  public string Value { get; set; }

  /// <summary>
  /// Create a new Combo Box object
  /// </summary>
  /// <param name="oName">Name of the object, will display in the ComboBox</param>
  /// <param name="oValue">Value of the object.</param>
  public cbItem(string oName, string oValue)
  {
   Name = oName;
   Value = oValue;
  }

  public override string ToString()
  {
   return Name;
  }
}

To use this to populate a ComboBox you can use something like this:

SqlCommand cmd = new SqlCommand("SELECT ClientID, ClientName FROM clients ORDER BY ClientName",
new SqlConnection(WMTClientMigration.Properties.Settings.Default.WMTDatabase));
   cmd.Connection.Open();
   SqlDataReader rdr = cmd.ExecuteReader();
   while (rdr.Read())    {    cbClients.Items.Add(new cbItem(rdr[1].ToString(), rdr[0].ToString()));   }

And, finally, you can access the data easily:

private void cbClients_SelectedIndexChanged(object sender, EventArgs e)
  {
   Console.WriteLine(cbClients.SelectedItem.ToString());
   Console.WriteLine(((cbItem)cbClients.SelectedItem).Value);
  }

Still, it would be a lot easier if this was built into a ComboBoxItem class by MSFT.

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment  Cancel 
 
 
  
 
Privacy Statement | Terms Of Use Copyright 2001-2008 by ReluctantDBA.com