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.
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"));
You can create own DataSource which will be automatically displayed in the VisualStudio toolbox along with other standard controls, if you really need such kind of data source try out following:
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>
You can use a DataTable for the data source (or other bindable source), and bind the DataTable to the RadioButton list. Use DataTextField and DataValueField properties to specify which column is used for text and which is used for the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With