How to return DropDownList selections dynamically in C#?

Posted by salvationishere on Stack Overflow See other posts from Stack Overflow or by salvationishere
Published on 2010-04-10T05:21:07Z Indexed on 2010/04/10 5:23 UTC
Read the original article Hit count: 638

Filed under:
|
|

This is probably a simple question but I am developing a web app in C# with DropDownList. Currently it is working for just one DropDownList. But now that I modified the code so that number of DropDownLists that should appear is dynamic, it gives me error;

"The name 'ddl' does not exist in the current context."

The reason for this error is that there a multiple instances of 'ddl' = number of counters. So how do I instead return more than one 'ddl'? Like what return type should this method have instead? And how do I return these values?

Reason I need it dynamic is I need to create one DropDownList for each column in whatever Adventureworks table they select.

      private DropDownList CreateDropDownLists()
    {
        for (int counter = 0; counter < NumberOfControls; counter++)
        {
            DropDownList ddl = new DropDownList();
            SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable);
            ddl.ID = "DropDownListID" + (counter + 1).ToString();

            int NumControls = targettable.Length;
            DataTable dt = new DataTable();
            dt.Load(dr2);

            ddl.DataValueField = "COLUMN_NAME";
            ddl.DataTextField = "COLUMN_NAME";
            ddl.DataSource = dt;
            ddl.ID = "DropDownListID 1";
            ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged);
            ddl.DataBind();

            ddl.AutoPostBack = true;
            ddl.EnableViewState = true; //Preserves View State info on Postbacks
            //ddlList.Style["position"] = "absolute";
            //ddl.Style["top"] = 80 + "px";
            //ddl.Style["left"] = 0 + "px";
            dr2.Close();
        }
        return ddl;
    }

© Stack Overflow or respective owner

Related posts about dropdownlist

Related posts about c#