how to create datasource for radiobuttonlist?

Steven Zack picture Steven Zack · Aug 5, 2011 · Viewed 16.3k times · Source

I want to create several items for radiobuttonlist by myself, the item has text and value properties. How to do it in c#/asp.net? Thanks in advance.

Answer

jdavies picture jdavies · Aug 5, 2011

You can us a Dictionary object to store the key/values and bind it to the RadioButtonList like so:

        Dictionary<string, string> values = new Dictionary<string, string>();
        values.Add("key 1", "value 1");
        values.Add("key 2", "value 2");
        values.Add("key 3", "value 3");

        RadioButtonList radioButtonList = new RadioButtonList();
        radioButtonList.DataTextField = "Value";
        radioButtonList.DataValueField = "Key";
        radioButtonList.DataSource = values;
        radioButtonList.DataBind();

Or you can also add the items to the RadioButtonList Items collection like so:

        radioButtonList.Items.Add(new ListItem("Text 1", "Value 1"));
        radioButtonList.Items.Add(new ListItem("Text 2", "Value 2"));
        radioButtonList.Items.Add(new ListItem("Text 3", "Value 3"));