【发布时间】:2011-10-21 04:04:08
【问题描述】:
我想自己为radiobuttonlist创建几个项目,项目有文本和值属性。如何在 c#/asp.net 中做到这一点?提前致谢。
【问题讨论】:
标签: c# asp.net radiobuttonlist
我想自己为radiobuttonlist创建几个项目,项目有文本和值属性。如何在 c#/asp.net 中做到这一点?提前致谢。
【问题讨论】:
标签: c# asp.net radiobuttonlist
您可以使用 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 属性来指定哪一列用于文本,哪一列用于值。
【讨论】: