Using a Dictionary as the DataSource for a DropDownList

  • Thread starter Thread starter Mark Rae
  • Start date Start date
M

Mark Rae

Hi,

Is it possible to use a Dictionary<int, string> or even Dictionary<string,
string> as the DataSource for a DropDownList directly, i.e. without having
to iterate through the the Dictionary's KeyValuePair collection and populate
the DropDownList's Items collection manually?

The DropDownList certainly "understands" the Dictionary object, but the
problem seems to be that there's no way of telling it which element of the
Dictionary object is the DataValueField and which the DataTextField.

Code example follows:

<!--HTML page-->
<asp:DropDownList ID="cmbDropDownList" Runat="server" />

//C# codefile
Dictionary<byte, string> dicTable = new Dictionary<byte, string>();
dicTable.Add(1, "One");
dicTable.Add(2, "Two");
dicTable.Add(3, "Three");
dicTable.Add(4, "Four");

cmbDropDownList.DataSource = dicTable;
//cmbDropDownList.DataTextField = how?
//cmbDropDownList.DataValueField = how?
cmbDropDownList.DataBind();

The above code doesn't generate any errors, but the DropDownList's Items
haven't "understood" how to separate the Dictionary's elements...

Obviously, the following code works perfectly...

cmbDropDownList.Items.Clear();
foreach (KeyValuePair<byte, string> objKVP in dicTable)
{
cmbDropDownList.Items.Add(new ListItem(objKVP .Value.ToString(), objKVP
..Key.ToString()));
}

but I'm curious as to whether it's possible for a DropDownList to actually
use a Dictionary as its DataSource.

Again, this is just a theoretical question for my own interest - I'm really
only interested to know if it's possible - not that there are other ways of
binding data to a DropDownList... :-)

Any assistance gratefully received.

Mark
 
The text member is "value" and the value member is "key" when using one of
these types of objects to bind to a DropdownList.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

*************************************************
Think outside the box!
*************************************************
 
Dont use a dictionary. Its better to use a datasource that is in
electronic format, or else you will need to retype in all of the data.
Alternatly you could try to OCR the dictionary.

The Master
 
Back
Top