Data in ComboBoxes

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How can data be stored in comboboxes similar to html pulldowns? I know I can
access the data of the combobox either by the items text or by its index.
However, I would like to have a pulldown representing something like:

Text: 1 minute; Value: 1
Text: 5 minutes; Value: 5
Text: 1 hour; Value: 60

Thanks. Dave.
 
You can do something like this if you use data binding. Simply setup your
comboBox as follows:

// fill your comboBox with data from a database
// SQL - select myValueMember, myDisplayMember from someTable
// *** code to fill dataset ***

comboBox1.DisplayMember = "myDisplayMember";
comboBox1.ValueMember = "myValueMember";
comboBox1.DataSource = ds.Tables[0];

In the SelectedIndexChanged event of the ComboBox you can then do:

object myValueMember = comboBox1.SelectedValue;
// or if you know the data type
int myValueMember = (int)comboBox1.SelectedValue;

Since ComboBoxes can be bound to any component that implements IListSource
or IList your imagination is the limit. The MSDN has a good example listed
under the ListControl.DataSource property (System.Windows.Forms).
 
The way I've handled this sort of thing is to create a Class (or Struct)
with a ToString() method that gives you the text you want. If you store
objects of this class in the ComboBox, it will display the text you want,
but when you get the selected item, you can cast it to your Class and access
member variables containing the underlying data. It's a cool feature of
DotNet that the item type is object and the control uses the ToString()
method to figure out how to display it.

Generally speaking, you probably want to write some code that determines how
to display a particular value (number of minutes). The only place to put
this is inside of a class, so this works out fine. Off the top of my head,
you could use something like this:

public class MyTimeSpan
{
private int m_iMinutes;
public MyTimeSpan(int minutes)
{
m_iMinutes = Math.Max(minutes, 0);
}
public string ToString()
{
string sTime = "";
int iMinutes = m_iMinutes;

int iWeeks = iMinutes \ 10080;
sTime += GetFormattedString(iWeeks, "week", "weeks");
iMinutes -= iWeeks * 10080;

int iDays = iMinutes \ 1440;
sTime += GetFormattedString(iDays, "day", "days");
iMinutes -= iDays * 1440;

int iHours = iMinutes \ 60;
sTime += GetFormattedString(iHours, "hour", "hours");
iMinutes -= iHours * 60;

sTime += GetFormatttedString(iMinutes, "minute", "minutes");
return sTime;
}
private string GetFormattedString(int count, string singular, string
plural)
{
if( iCount <= 0 )
return "";
return string.Format("{0} {1}", iCount, ( iCount == 1 )? singular :
plural);
}
}
 
Back
Top