Answered by:
How to dynamically (in code behind) add key/value pair to dropdown combo box in asp.net 2.0 C#

Question
-
User193260626 posted
I have my data in the form of a Dictionary List object (key/value pair). I want to populate a dropdown combo box with this object with both the key and value as the combo box index and value respectively. It seems to be not that easy in asp.net 2.0 C#. I am able to add just the value as follows:
foreach
(KeyValuePair<int, string> kvp in states) {cboStates.Items.Add(kvp.Value.ToString());
}
In the above sample "states" is the Dictionary object. But I don't know how to add the key as the index in the combo box. I saw an article in VB.Net (http://aspalliance.com/1059_CodeSnip_How_to_Add_DataValues_for_Corresponding_Entries_in_a_Combo_Box_Using_Visual_Basic_NET.1 ) which creates a fake object with the key/value pair, and adds the object to the Items colletion of the combo box. But this method didn't work in C#.
{
cboState.Items.Add(
new AddToComboBox(Convert.ToInt32(kvp.Key), Convert.ToString(kvp.Value)));}
where AddToComboBox is the fake object with key/value as public properties. When I tried this I got, "The best overloaded method match for 'System.Web.UI.WebControls.ListItemCollection.Add(string)' has some invalid arguments" error. Any help is greatly appreciated.
Thanks
Wednesday, September 19, 2007 5:18 PM
Answers
-
User849259894 posted
foreach (KeyValuePair<int, string> kvp in states) { cboStates.Items.Add(New ListItem(kvp.Value.ToString(), kvp.Key.ToString()) ; }
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, September 19, 2007 6:10 PM
All replies
-
User849259894 posted
foreach (KeyValuePair<int, string> kvp in states) { cboStates.Items.Add(New ListItem(kvp.Value.ToString(), kvp.Key.ToString()) ; }
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, September 19, 2007 6:10 PM -
User193260626 posted
Thanks a lot. It worked!
Wednesday, September 19, 2007 7:33 PM -
User1736992962 posted
I have my data in the form of a Dictionary List object (key/value pair). I want to populate a dropdown combo box with this object with both the key and value as the combo box index and value respectively.Try This :
ddlAnuraktiRoles.DataSource = dictionaryObject; ddlAnuraktiRoles.DataTextField = "Key"; ddlAnuraktiRoles.DataValueField = "Value"; ddlAnuraktiRoles.DataBind();
Cheers!
Gaurav.
Anurakti Solutions!
www.Anurakti.comMonday, July 25, 2011 3:01 AM