简体   繁体   中英

How to populate a dropdown list with SQL values in ASP.net Web application

I'm new to ASP.net and I'm trying to populate a dropdown list with values from a local SQL Database in Visual Studio.

This is the code I have but Its not working, could anyone assist?

           {
            SqlConnection PopulateListCon = new SqlConnection(ConnectionString);
                try
                {
                    if (PopulateListCon.State == ConnectionState.Closed)
                        PopulateListCon.Open();
                    String query = "SELECT * FROM ModuleTable WHERE UserId=@User AND ModuleSemester=@Sem";
                    SqlCommand sqlCmd = new SqlCommand(query, PopulateListCon);
                    sqlCmd.Parameters.Add("@User", SqlDbType.VarChar);
                    sqlCmd.Parameters["@User"].Value = userIdentification;
                    sqlCmd.Parameters.Add("@Sem", SqlDbType.VarChar);
                    sqlCmd.Parameters["@Sem"].Value = semester;

                    SqlDataReader dr1 = sqlCmd.ExecuteReader();
                    while (dr1.Read())
                    {
                        string modName = dr1.GetString(3);
                        Ddl_Module_Info_Time_Allocation_Module_Code.Items.Add(modName);
                    }
                }
                catch (Exception ex)
                {
                    errMsg = ex.Message;
                    Response.Write("<script>alert('Error: " + errMsg + "')</script>");
                }
                finally
                {
                    PopulateListCon.Close();
                }
        }

this is the Code for the Drop Down List:

<asp:DropDownList ID="Ddl_Module_Info_Time_Allocation_Module_Code" runat="server" style="z-index: 3; left: 330px; top: 10px; position: absolute" Height="24px" Width="128px" Visible="False"></asp:DropDownList>

If anyone could assist it would be appreciated

Your code is close. but you should show the markup for the drop down list.

Like desktop (FoxPro, MS-Access, vb.net, c#), a combo box (drop down list) has the ability to deal with TWO columns.

 DataValueField = "column name" - this is the "ID" or often PK from table
 DataTextField = "column name"  - this is the text "display" column from table

So, say I need a drop down of Hotel Names. And say only hotels from a given city.

So the markup is this:

   <div>
        <asp:DropDownList ID="DropDownList1" runat="server" Width="128px"
            DataValueField = "ID"
            DataTextField = "HoteName"
            >                
        </asp:DropDownList>
        <br />

And the above also lets me go SELECT * from some table, since which column is supposed to fill which setting in the drop down list?? (so, that's what DataValue and DataText settings above do).

Now, our code would be this:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadCombo();
    }

    void LoadCombo()
    {

        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string testcity = "Banff";    // this could be some user input - whatever
            string strSql = "SELECT ID, HotelName FROM tblHotels Where City = @City";

            using (SqlCommand cmdSQL = new SqlCommand(strSql, conn))
            {
                cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = testcity;
                conn.open();
                DropDownList1.DataSource = cmdSQL.ExecuteReader();
                DropDownList1.DataBind();
            }
        }
    }

So, your code for this could/would be this:

            using (SqlConnection PopulateListCon = new SqlConnection(ConnectionString))
            {
                string strquery = "SELECT * FROM ModuleTable";
                using (SqlCommand sqlCmd = new SqlCommand(strquery, PopulateListCon))
                {
                PopulateListCon.Open();
                Ddl_Module_Info_Time_Allocation_Module_Code.DatSource = sqlCmd.ExecuteReader();
                Ddl_Module_Info_Time_Allocation_Module_Code.DataBind();
                }
            }

The above is without parameters.

For parameters, say your this:

           using (SqlConnection PopulateListCon = new SqlConnection(ConnectionString))
            {
              string query = "SELECT * FROM ModuleTable WHERE UserId=@User AND ModuleSemester=@Sem";

                using (SqlCommand sqlCmd = new SqlCommand(strquery, PopulateListCon))
                {
                    sqlCmd.Parameters.Add("@User", SqlDbType.Int).Value = User_ID;
                    sqlCmd.Parameters.Add("@Sem", SqlDbType.Int).Value = some sem expression here;

                    PopulateListCon.Open();
                    Ddl_Module_Info_Time_Allocation_Module_Code.DatSource = sqlCmd.ExecuteReader();
                    Ddl_Module_Info_Time_Allocation_Module_Code.DataBind();
                }
            }

Then our code would be:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM