nikta
nikta

Reputation: 79

populate dropdown from class

I have several static asp.net dropdown in my aspx page (state, year,Day, month). I like to create a class and list of values instead of having all this in my page, call that class to populate dropdown.
This is for example state dropdown that I need to populate:

<asp:ListItem value="">State</asp:ListItem>
<asp:ListItem value="">Select</asp:ListItem>
<asp:ListItem value="AL" >Alabama</asp:ListItem>
<asp:ListItem value="AK" >Alaska</asp:ListItem> ....

I have created this class:

public class State
{
    public string StateValue { get; set; }
    public string StateName { get; set; }

    public List<State> StateList()
    { 
        return new List<State> 
        { 
            new State{StateValue="",StateName="Select" }
            ,new State{StateValue="AL",StateName="Alabama"}
            ,new State{StateValue="AK",StateName="Alaska"}
        }
    };
}

and in my page I call the class like this:

State state = new State();
stateddl.DataSource = state.StateList().ToList();
stateddl.DataTextField = state.StateName;
stateddl.DataValueField = state.StateValue;

but I m getting empty dropdown. Where you think it is a problem?

I forgot to put stateddl.DataBind(); it works now thanks.

Upvotes: 2

Views: 1709

Answers (1)

Claudio Redi
Claudio Redi

Reputation: 68440

I see two problems

1) You're specifying wrong DataTextField and DataValueField

2) You're probably never binding the data source

Use this instead

stateddl.DataSource = state.StateList(); // No need to use ToList()
stateddl.DataTextField = "StateName"; // Specify the name of the text field
stateddl.DataValueField = "StateValue"; // Specify the name of the value field
stateddl.DataBind(); // <-- Bind the data source

Upvotes: 3

Related Questions