這是我的ADO.NET代碼如何在GridView中的按鈕單擊事件的文本框中輸入可空int後驗證?
protected void AddToCart_Click(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
int index = gvr.RowIndex;
TextBox box1 = (TextBox)GridView1.Rows[index].Cells[9].FindControl("TextBox1");
int? Quantity = Convert.ToInt32(box1.Text);
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
string ToyId = row.Cells[0].Text;
string CS1;
CS1 = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Toy_WebForm; integrated security=SSPI";
SqlConnection con1 = new SqlConnection(CS1);
SqlCommand cmd1 = new SqlCommand("QuantityValidation", con1);
cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("@ToyNo", ToyId);
con1.Open();
int ToyQuantity = Convert.ToInt32(cmd1.ExecuteScalar());
con1.Close();
if (Quantity <= ToyQuantity && Quantity > 0)
{
string CS2;
CS2 = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Toy_WebForm; integrated security=SSPI";
SqlConnection con2 = new SqlConnection(CS2);
SqlCommand cmd2 = new SqlCommand("AddToCart", con2);
cmd2.CommandType = System.Data.CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("@ToyNo", ToyId);
cmd2.Parameters.AddWithValue("@MemberNo", MemberId);
cmd2.Parameters.AddWithValue("@TotalQuantity", Quantity);
con2.Open();
SqlParameter OutputParameter1 = new SqlParameter();
OutputParameter1.ParameterName = "@CartNo";
OutputParameter1.SqlDbType = System.Data.SqlDbType.UniqueIdentifier;
OutputParameter1.Direction = System.Data.ParameterDirection.Output;
cmd2.Parameters.Add(OutputParameter1);
SqlParameter OutputParameter2 = new SqlParameter();
OutputParameter2.ParameterName = "@TotalPrice";
OutputParameter2.SqlDbType = System.Data.SqlDbType.Int;
OutputParameter2.Direction = System.Data.ParameterDirection.Output;
cmd2.Parameters.Add(OutputParameter2);
cmd2.ExecuteNonQuery();
con2.Close();
string TotalPrice = OutputParameter2.Value.ToString();
Label lbl1 = (Label)GridView1.Rows[index].Cells[10].FindControl("Label4");
lbl1.Text = TotalPrice + " RM";
Label3.Text = "Added to cart";
}
else if (Quantity>ToyQuantity)
{
Label3.Text = "Please enter within the stock limit";
}
else if (Quantity == 0 || Quantity == null)
{
Label3.Text = "Please add at least one quantity";
}
}
所有if和else if條件,成功地工作添加到購物車按鈕點擊事件。 但是,如果你看看過去的,如果條件:
else if (Quantity == 0 || Quantity == null)
{
Label3.Text = "Please add at least one quantity";
}
else if(Quantity == 0)
正在執行成功添加到購物車按鈕點擊事件。 然而,else if (Quantity == null)
沒有被添加到購物車按鈕點擊事件執行,它顯示在下面的行錯誤:
int? Quantity = Convert.ToInt32(box1.Text);
上方直線的錯誤說
「輸入字符串不是以正確的格式。「
我可以得到一個示例代碼來解決這個特定問題嗎?