Stc5097
Stc5097

Reputation: 289

Populating a drop down list with c# code behind

I am trying to populate a drop down list using code behind (C#). I am not sure how to get this. Below is my code that I am currently trying to use but I am getting errors. I am trying to populate a drop down list the stores the months ( 1 - 12).

protected void Page_Load(object sender, EventArgs e)
{

  for (int i = 0;  i < 12; i++)
    {

        DropDownListMonth.SelectedValue = i;
        DropDownListMonth.DataTextField = i.ToString();
        DropDownListMonth.DataValueField = i.ToString();
    }

}

Upvotes: 0

Views: 28856

Answers (3)

wingyip
wingyip

Reputation: 3536

This is what you need to do

for (var i = 1; i < 13; i++)
{
    var item = new ListItem
        {
            Text = i.ToString(),
            Value = i.ToString()
        };
    DropDownListMonth.Items.Add(item);
}

Upvotes: 3

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

Sounds like you just need to add items in your dropdownlist. How about using List<int> with foreach loop like;

List<int> months = new List<int>(){1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
foreach (string month in months)
{
     DropDownListMonth.Items.Add(month);
}

Because your for loop works 0 to 11 not 1 to 12. And it is not adding any item. It just sets SelectedValue, DataTextField and DataValueField as 11, doesn't do anything more.

Upvotes: 3

Noctis
Noctis

Reputation: 11763

You want to have a list, add the values to that list, and have that list bound to the dropdown.

Also, have a look at this article to clear up some confusion: selected item, value, and more

Upvotes: 0

Related Questions