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.ToString());
}

Now this displays 1 on page load ... but I want to display 7.. How do I do that?

13.10.2009 16:52:19
4 ОТВЕТА
РЕШЕНИЕ

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"
    }
}
2
13.10.2009 16:55:24
just perfect.. and thanks for the postback info.... it helped me in figuring out many things...
user175084 13.10.2009 17:00:37

Use the SelectedItem or SelectedIndex property.

0
13.10.2009 16:54:32

After your for loop

DropDownList1.Items.FindByText("7").Selected = true;
1
13.10.2009 16:57:44

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); 
     }
}
2
13.10.2009 18:06:37