display a particular number from dropdownlist
Is there a way in dropdownlist to show the desired number on pageload?
eg. I have a dropdownlist control
I am using a for loop to populate it
for (int i = 1; i <= 100; i++)
{
DropDownList1.Items.Add(i.T开发者_JAVA百科oString());
}
Now this displays 1 on page load ... but I want to display 7.. How do I do that?
If you mean that it is the default selected value, you would just need to set a default selected value in the page load, after the list has been populated. Make sure only to do this when it is not a postback or you will overwrite any user selections.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.SelectedValue = "7"
}
}
Would set it inside your for loop. Would also store the default somewhere outside the code (db, config) so if it changes you don't have to redeploy.
if(!IsPostBack)
{
for (int i = 1; i <= 100; i++)
{
var newItem = new ListItem(i.ToString());
newItem.Selected = (i == 7);
DropDownList1.Items.Add(newItem);
}
}
After your for
loop
DropDownList1.Items.FindByText("7").Selected = true;
Use the SelectedItem or SelectedIndex property.
精彩评论