Radiobutton list select an Item on page Load
I have a radiobuttonlist that i am populating on 开发者_开发百科runtime with a datasource. Now what I want is to select the item that has text "Daily At" by default when page is loaded. How to achieve this?
foreach (ListItem item in RadioButtonList1.Items)
{
if (item.Text.Contains("Daily At"))
{
item.Selected = true;
break;
}
}
Set SelectedValue property.
if(!IsPostBack)
{
....
RadioButtonList1.DataBind();
RadioButtonList1.SelectedValue="Daily At";
}
You can use SelectedIndex property.
if(!IsPostBack)
{
....
RadioButtonList1.DataBind();
RadioButtonList1.SelectedIndex=1;
}
Here is sample for your reference:
public class Data
{
public int No { get; set; }
public string Name { get; set; }
}
Code in Page_Load event
if (!IsPostBack)
{
List<Data> list = new List<Data>()
{
new Data() { Name="Test1", No=10},
new Data() { Name="Test2", No=20},
new Data() { Name="Test3", No=30}
};
RadioButtonList1.DataSource = list;
RadioButtonList1.DataTextField = "Name";
RadioButtonList1.DataValueField = "No";
RadioButtonList1.DataBind();
RadioButtonList1.SelectedValue = "30";
}
Try this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RadioButtonList.DataBind();
RadioButtonList.Items.FindByText("Daily At").Selected=true;
}
}
精彩评论