Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate dropdown list before page loads in webforms?

I have the following Page_Load method in my control (System.Web.UI.UserControl):

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList ShowAssumptions = new DropDownList();
    List<string> list = new List<string>()
    {
        "test",
        "test2"
    };
    ShowAssumptions.DataSource = from i in list
                                 select new ListItem()
                                 {
                                     Text = i,
                                     Value = i
                                 };
    ShowAssumptions.DataBind();
}

Then, in my .aspx I have this:

<asp:DropDownList id="ShowAssumptions" runat="server">
</asp:DropDownList>

But, the DropDownList never gets populated. What am I doing wrong?

like image 583
user1477388 Avatar asked May 01 '14 16:05

user1477388


2 Answers

Just assign the list as the datasource. Also I assume you don't want to reload the list on every PostBack.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
         List<string> list = new List<string>()
         {
            "test",
            "test2"
         };
        ShowAssumptions.DataSource = list;
        ShowAssumptions.DataBind();
    }
}
like image 52
Tsukasa Avatar answered Oct 16 '22 09:10

Tsukasa


In case if you use ASP.NET WebForms, EF and Bootstrap try this

HTML

<div class="form-group">    

<label class="control-label" for="inputType">Lines: </label>                            

<asp:DropDownList ID="DropDownListFabricLines" CssClass="dropdown form-control" runat="server"></asp:DropDownList>

</div>

C#

var entities = new DababaseEntities();

List<FabricLineView> fabricLines =  entities .Line.Select(x=> new FabricLineView { ID = x.LineaID, Name = x.LineaNombre }).ToList();

DropDownListFabricLines.DataValueField = "ID";
DropDownListFabricLines.DataTextField = "Name";
DropDownListFabricLines.DataSource = fabricLines;
DropDownListFabricLines.DataBind();


public sealed class FabricLineView
{
    public int ID { get; set; }
    public string Name { get; set; }
}
like image 41
Friend Avatar answered Oct 16 '22 10:10

Friend