![](/img/trans.png)
[英]How can I create a List with foreach and add items to radiobuttonlist alphabetical
[英]how to create datasource for radiobuttonlist?
我想自己为radiobuttonlist创建几个项目,该项目具有文本和值属性。 怎么在c#/ asp.net中做到这一点? 提前致谢。
您可以使用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();
或者您也可以将项添加到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"));
您可以创建自己的DataSource,它将与其他标准控件一起自动显示在VisualStudio工具箱中,如果您真的需要这样的数据源,请尝试以下操作:
public class CustomDataSource : System.Web.UI.WebControls.ObjectDataSource
{
public CustomDataSource()
{
// Hook up the ObjectCreating event so we can use our custom object
ObjectCreating += delegate(object sender, ObjectDataSourceEventArgs e)
{
// Here we create our custom object that the ObjectDataSource will use
e.ObjectInstance = new DataAccessor()
};
}
class DataAccessor
{
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Add(string text, string value)
{
// Insert logic
}
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int id, string text, string value)
{
// Update logic
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public IEnumerable<MyRadioButtonEntryWrapper> List(int filterById)
{
// Select logic
}
}
ASPX:
<%@ Register TagPrefix="cc1" Namespace="DataLayer.DataSources" %>
<cc1:CustomDataSource ID="customDataSource" runat="server"
TypeName="DataAccessor"
OldValuesParameterFormatString="original_{0}"
InsertMethod="Add"
UpdateMethod="Update">
<UpdateParameters>
<asp:Parameter Name="id" Type="Int32" />
<asp:Parameter Name="text" Type="String" />
<asp:Parameter Name="value" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="text" Type="String" />
<asp:Parameter Name="value" Type="String" />
</InsertParameters>
</cc1:ArticleTypeDataSource>
您可以将DataTable用于数据源(或其他可绑定源),并将DataTable绑定到RadioButton列表。 使用DataTextField和DataValueField属性指定用于文本的列以及用于该值的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.