简体   繁体   中英

How can I make a DropDownList from the database?

When I choose any option from the dropdown list and then insert it into the database, the first option is chosen automatically, even if I choose the second or third option; only the first option is inserted each time.

Order.aspx.cs

protected void selectList()
        {
            conn = new SqlConnection(connstr);
            conn.Open();
            sql = "SELECT * FROM Product";
            SqlCommand comm = new SqlCommand(sql, conn);
            adap = new SqlDataAdapter(comm);
            DataSet ds = new DataSet();
            adap.Fill(ds);
            ProductID.DataTextField = ds.Tables[0].Columns["Name"].ToString();
            ProductID.DataValueField = ds.Tables[0].Columns["Id"].ToString();
            ProductID.DataSource = ds.Tables[0];
            ProductID.DataBind();
        }

    protected void Page_Load(object sender, EventArgs e)
        {
            bindGrid();
            selectList();

        }

     protected void btnAdd_Click(object sender, EventArgs e)
        {
            selectList();
            sql = "INSERT INTO [Order] (CustomerID,ProductID ,EmployeeID,Quantity,Date) VALUES ('" + CustomerID.Text + "','" + ProductID.SelectedValue + "','" + EmployeeID.Text + "','" + Quantity.Text + "','" + Date.Text +  "')";
            conn = new SqlConnection(connstr);
            conn.Open();
            comm = new SqlCommand(sql, conn);
            comm.ExecuteNonQuery();
            conn.Close();
            bindGrid();
            ScriptManager.RegisterStartupScript(Page, Page.GetType(),
                "myPrompt", "alert('Successfully Updated!');", true);
        }

Order.aspx

   Product ID:
         <asp:DropDownList ID="ProductID" runat="server"  CssClass="form-control" ></asp:DropDownList>

Actually, the mistake here is the page load. In 99% of ALL pages, you only want to bind and load up on the first page load. And most if not all asp controls will automatic persist for you. So, your big mistake is this:

protected void Page_Load(object sender, EventArgs e)
    {
        bindGrid();
        selectList();

    }

The above has to become this:

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

In fact, you really can't build a functional web form page unless you follow the above rule. Remember, any button, any post-back, and the page load event will run again.

So yes, page load is the right place, but you in near 99% of cases need to wrap that code in the all important isPostBack = false code stub.

Once you do above, then your whole page will operate quite nice, quite normal, and in near all cases, you find the controls correct persist their values and settings.

So, no, page load is NOT too soon, and page load is VERY much the correct event and place to load up the data bound controls - but, you only want to do this on the really first page load.

In fact, there is probably 1 question near per day on SO, and their woes and problems can be fixed by following the above simple rule. Failure to note the above isPostBack? You can't really even build a working asp.net page.

Page_Load() is too late to bind your list .

Remember, when using web forms, you start from scratch and have to recreate all of your data items on every single request... even simple button click events * . This is why you call bindGrid() in the Page_Load() method. However, part of this process also involves restoring ViewState , so the button click will know what item was selected. The problem is this ViewState data is restored before the Page_Load() method is called. Therefore the grid is still empty , and the SelectedValue information you need to get from ViewState cannot be set correctly.

You can fix this by moving the code that binds your grid data up to the Init or Pre_Init events.

While I'm here, I need to reiterate my comment about SQL Injection. This is a really big deal ... the kind of thing that's too important to do wrong even with learning and proof-of-concept projects. I suggest using Google to learn more about using parameterized queries with C#.

Additionally, it's rare to insert selections directly into an Orders table. Often there's a separate "ShoppingCart" table, using a Session Key for the table's primary key, where the user can build up the cart before completing the order and creating the final Order and OrderLines or OrderDetail records.


* For this reason, it's often worthwhile in web forms to do more of this work on the client browser, in javascript.

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