如何为radiobuttonlist创建数据源?

Ste*_*ack 12 c# asp.net radiobuttonlist

我想自己为radiobuttonlist创建几个项目,该项目具有文本和值属性.怎么在c#/ asp.net中做到这一点?提前致谢.

jda*_*ies 16

您可以使用Dictionary对象来存储键/值并将其绑定到RadioButtonList,如下所示:

        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();
Run Code Online (Sandbox Code Playgroud)

或者您也可以将项添加到RadioButtonList Items集合中,如下所示:

        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"));
Run Code Online (Sandbox Code Playgroud)