2

I'm binding a Dictionary to a drop down list.

Say for example I have the following items in dictionary:

{"Test1", 123}, {"Test2", 321} 

I'd like the drop down text to take the following format:

Test1 - Count: 123
Test2 - Count: 321

I was going along the following path with no luck:

MyDropDown.DataTextFormatString = string.Format("{0} - Count: {1}", Key, Value);

Thank you :)

timothyclifford
  • 6,799
  • 7
  • 57
  • 85

3 Answers3

5

You could create a projection view by using LINQ on your dictionary and create an anonymous type to hold your custom formatting.

Dictionary<string, int> values = new Dictionary<string, int>();
values.Add("First", 321);
values.Add("Second", 456);
values.Add("Third", 908);


var displayView = from display in values
                    select new { DisplayText = display.Key + " Count: " + display.Value };

DropDownList1.DataSource = displayView;
DropDownList1.DataTextField = "DisplayText";
DropDownList1.DataBind();
ChristiaanV
  • 5,401
  • 3
  • 32
  • 42
1

I don't think that the DropDownList does support DataTextFormatString s that concat a String like you want to do it. As far as I know, you can only use format strings for numbers and dates. (For examples see here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datatextformatstring.aspx)

You can either do it the way ChristiaanV proposes (anonymous type), or you use your own POCO class (class only containing properties).
Be aware that using anonymous types have a limited scope. You can't usem them in a BusinessLayer-Assembly and have the GUI-Assembly use the result, because the ability of returning an anonymous type from a method are very limited.

I'd suggest you do something like this:

public class MyPOCO
{
  public int MyPrimaryKey {get;set;}
  public String DisplayString {get;set;}
}

Create a List<MyPOCO> in your code and bind it to the DataSource property. Set the DataValueField to MyPrimaryKey and the DataTextField to DisplayString

If you are having problems with your databinding on postbacks, you can do the following:

  1. Create a method that returns a List<MyPOCO>
  2. Create a ObjectDataSource and use the wizard to select the methods you created in 1.
  3. Assign the ID of the ObjectDataSource to the DataSourceID of the DropDownList.
citronas
  • 19,035
  • 27
  • 96
  • 164
1

You cannot use string.Format in

DataTextFormatString

Try the following code.

Dictionary<string, int> s = new Dictionary<string, int>();
        s.Add("Test1", 123);
        s.Add("Test2", 321);

        foreach(KeyValuePair<string,int> temp in s)
        {
            DropDownList1.Items.Add(new ListItem(string.Format("{0} - Count: {1}", temp.Key, temp.Value),temp.Value.ToString()));
        }
varadarajan
  • 514
  • 1
  • 3
  • 9