我有一个DropDownList,我把它绑定到一个表。问题是当我尝试将dropDownlist控件的选定值插入数据库时,我没有得到正确的值而是将整数数据作为2和1。
这是我的dropdownList控件:
<asp:DropDownList
ID="ddlproductName"
runat="server"
DataTextField="Prod_Name"
DataValueField= "Product_Id"
>
</asp:DropDownList>
代码隐藏:
protected void Page_Load(object sender, EventArgs e)
{
ddlproductName.SelectedIndex = 0;
if (!IsPostBack)
{
tbDate.Text = DateTime.Today.ToShortDateString();
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select Product_Id,Prod_Name from Add_Product", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
ddlproductName.DataSource = rdr;
ddlproductName.DataBind();
}
}
}
protected void btnPurchase_Click(object sender, EventArgs e)
{
try
{
string custName = tbcustName.Text;
string prodName = ddlproductName.SelectedValue;
int quantity = Convert.ToInt32(tbQuantity.Text);
string date = tbDate.Text;
string voucherNo = tbVoucher.Text;
double amount = Convert.ToDouble(tbAmount.Text);
PurchProduct purch = new PurchProduct(custName, prodName, quantity, date, voucherNo, amount);
ConnectionClass.purchaseProd(purch);
LblPurchase.Text = "Submitted succesfully";
}
buyProd方法如下:
public static void purchaseProd(PurchProduct purchase)
{
cmd = new SqlCommand("insert into TblPurchase(custName, prodName, quantity, date,voucherNo,amount) values (@custName, @prodName, @quantity, @date,@voucherNo,@amount)", con);
cmd.Parameters.AddWithValue("@custName", purchase.custName);
cmd.Parameters.AddWithValue("@prodName", purchase.prodName);
cmd.Parameters.AddWithValue("@quantity", purchase.quantity);
cmd.Parameters.AddWithValue("@date", purchase.date);
cmd.Parameters.AddWithValue("@voucherNo", purchase.voucherNo);
cmd.Parameters.AddWithValue("@amount",purchase.amount);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
cmd.Parameters.Clear();
}
}
答案 0 :(得分:0)
看起来您使用Product_ID作为SelectedValue,在下拉列表中将SelectedValue更改为Prod_Name。
答案 1 :(得分:0)
如果要从选定值获取产品名称,则应将其绑定为DataValueField而不是DataTextField