我在数据列表中有一个Dropdownlist
和一个按钮。我从下拉列表中选择项目数,然后将其传递给按钮事件以将其发送到数据库。
但我无法这样做。问题是变量selectedValue
只在内部分配dditem_change
,尽管我已经在全局范围内声明了它。
如何在DataList1_ItemCommand(object source, DataListCommandEventArgs e)
.
这是下拉列表更改的代码
public void dditem_change(object sender, EventArgs e)
{
var ddlList = (DropDownList)sender;
selectedValue = ((DropDownList)ddlList.NamingContainer.FindControl("drplist")).SelectedValue;
}
这是 public void DataList1_ItemCommand 的代码
public void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if(e.CommandName == "Add")
{
if (Session["user"] == null)
{
Response.Write("<script>alert('Login First!!!');</script>");
}
else
{
string[] ar = e.CommandArgument.ToString().Split(',');
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DTPXP-77A;Initial Catalog=practice;Integrated Security=true";
con.Open();
SqlCommand cmd = new SqlCommand("insert into cart values(@username,@prodname,@price,@stock)", con);
cmd.Parameters.Add("@username", SqlDbType.VarChar);
cmd.Parameters.Add("@prodname", SqlDbType.VarChar);
cmd.Parameters.Add("@price", SqlDbType.Int);
cmd.Parameters.Add("@stock", SqlDbType.Int);
cmd.Parameters["@username"].Value = Session["user"].ToString();
cmd.Parameters["@prodname"].Value = ar[0].ToString();
cmd.Parameters["@price"].Value = int.Parse(ar[1]);
cmd.Parameters["@stock"].Value = //selectedValue NOT ACCESSIBLE//
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Successfully Added');</script>");
}
}
}