我使用以下代码首先从category Id
检索category entity
并将其绑定到dropdownlist
DropDownlistCategory
。现在我要插入category ID
从dropdownlist到产品实体,其中包含数据库中的四列,如
ProductName,CategoryID,QuantityPerUnit and UnitPrice.
但是在插入dropdownlist值时,它将始终从下拉列表中选择第一个值。
使用此:
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");
}
答案 0 :(得分:3)
在页面加载中使用 IsPostBack 。仅在第一次加载页面时绑定下拉列表。
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//.... code to bind the dropdownlist
}
}