How to insert selected dropdownlist value into database using asp.net object data model

I used the code below for the first extraction category Idfrom category entityand attached it to dropdownlistwhich is DropDownlistCategory. Now I want to insert this category Idfrom the drop-down list into a product object that contains four columns in the database, for example

ProductName,CategoryID,QuantityPerUnit and UnitPrice.

But when inserting a dropdownlist value, it will always select the first value from the drop-down list.

Using this:

prod.CategoryID = Convert.ToInt32(DropDownListCategory.SelectedValue);

Is it correct?

Code NewProduct.aspx: -

 <asp:DropDownList ID="DropDownListCategory" runat="server"CssClass="form-    control" Width="100px"   OnSelectedIndexChanged="DropDownListCategory_SelectedIndexChanged" >

    </asp:DropDownList>

Code NewProduct.cs: -

    LaunderDBEntities context = new LaunderDBEntities(); 
    protected void Page_Load(object sender, EventArgs e)
    {

        var categoryId = from cat in context.Categories
                       select new
                       {

                           categoryID = cat.CategoryID,

                       };


        DropDownListCategory.DataSource = categoryId.ToList();
        DropDownListCategory.DataValueField = "categoryID";
        DropDownListCategory.DataTextField = "categoryID";
        DropDownListCategory.DataBind();
    }
    protected void btnAddProduct_Click(object sender, EventArgs e)
    {
        SaveProductInfo();
    }


    private void SaveProductInfo()
    {
        Product prod = new Product();
        prod.ProductName = txtProductName.Text;

        prod.CategoryID =   Convert.ToInt32(DropDownListCategory.SelectedValue);

        prod.QuantityPerUnit = Convert.ToInt32(txtQuantity.Text);
        prod.UnitPrice =Convert.ToInt32(txtUnitPrice.Text);


        ProductDA prdDa = new ProductDA();
        prdDa.InertProductDetails(prod);

        Label5.Text = "<p style='color:Green;'>Information Successfully saved!</p>";

        Response.Redirect("ProductInfo.aspx");

    }
+4
source share
1 answer

IsPostBack . .

 protected void Page_Load(object sender, EventArgs e)
 {
        if(!IsPostBack)
        { 
             //.... code to bind the dropdownlist

        }
}
+3

Source: https://habr.com/ru/post/1605881/


All Articles