2015-09-04 23 views
4

插入選擇下拉列表值到數據庫實體包含在數據庫中的四列如如何使用我用下面的代碼首先從<code>category entity</code>檢索<code>category Id</code>並將其綁定到<code>dropdownlist</code>是<code>DropDownlistCategory</code>。現在我想插入<code>category ID</code>從下拉列表產品asp.net實體數據模型

ProductName,CategoryID,QuantityPerUnit and UnitPrice. 

但同時插入下拉列表值將始終選擇從下拉列表的第一個值。

使用此:

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

它是正確的嗎?

NewProduct.aspx代碼: -

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

    </asp:DropDownList> 

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

    } 

回答

3

使用IsPostBack在頁面加載。僅在第一次加載頁面時綁定下拉列表。

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

     } 
} 
+0

由於它works..please投票了,如果我的問題是有幫助的。 –

相關問題