如何为单选按钮列表创建数据源
本文关键字:创建 数据源 列表 单选按钮 | 更新日期: 2023-09-27 18:04:34
我想自己为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"));
您可以创建自己的数据源,它将与其他标准控件一起自动显示在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属性指定哪一列用于文本,哪一列用于值。