Swapnil  Kachare
Swapnil Kachare

Reputation: 203

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

I have used below code to first retrieve category Id from category entity and bind it to the dropdownlist that is DropDownlistCategory .Now I want to insert that category ID from dropdownlist to product entity which contains four columns in the database such as

ProductName,CategoryID,QuantityPerUnit and UnitPrice.

But while inserting dropdownlist value it will always select the first value from dropdownlist.

Using this :

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

Is it correct?

NewProduct.aspx code:-

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

    </asp:DropDownList>

NewProduct.cs code:-

    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");

    }

Upvotes: 4

Views: 3595

Answers (1)

Sain Pradeep
Sain Pradeep

Reputation: 3125

Use IsPostBack in page load. Bind dropdown list only when page is load first time.

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

        }
}

Upvotes: 3

Related Questions