在下面的代码中,我正在尝试验证文本框(txt_quantity 和 txt_discount)但是MessageBox.Show("Cannot be empty");我没有得到这个,而是得到了错误('输入字符串的格式不正确。')我在这里忘记了什么吗?txt_数量(整数)txt_discount(十进制)decimal Discount, DiscountTotal, Discountgiven, Total;int Cost, Quantity, ID; byte[] data;public void Imagedisplay(){ using (var con = SQLConnection.GetConnection()) { using (var selects = new SqlCommand("Select * from employee_product where Codeitem =@Codeitem ", con)) { selects.Parameters.Add("@Codeitem", SqlDbType.VarChar).Value = _view.txt_code.Text; using (var reader = selects.ExecuteReader()) { while (reader.Read()) { data = (byte[])reader["Image"]; Cost = Convert.ToInt32(reader["Unitcost"]); Convert.ToInt32(DiscountTotal); // This is where i'm getting the error at Quantity = Convert.ToInt32(txt_quantity.Text); Discount = Convert.ToDecimal(txt_discount.Text); // Discountgiven = Cost * (Discount / Convert.ToDecimal(100)); DiscountTotal = Cost - Discountgiven; Total = DiscountTotal * Quantity; } } } }}private void btn_ok_Click(object sender, EventArgs e){ Imagedisplay(); using (var con = SQLConnection.GetConnection()) { if (string.IsNullOrEmpty(txt_quantity.Text) || string.IsNullOrEmpty(txt_discount.Text)) { MessageBox.Show("Cannot be empty"); } else { { command.Parameters.Add("@Date", SqlDbType.VarChar).Value = date; command.Parameters.Add("@Image", SqlDbType.VarBinary).Value = data; command.ExecuteNonQuery(); Totals(); } } } }
1 回答

一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
使用 NumericUpDown 而不是文本框来捕获整数/十进制值。它为您处理所有验证,以阻止用户输入非数字值。您可以设置所需的最大值和最小值,并且不必担心没有输入任何值,因为 NumericUpDown 将始终具有默认值。
如果您使用整数,则只需在检索值时转换为 int,否则返回小数。所以你的代码是:
Quantity = Convert.ToInt32(numericupdown1.Value);
Discount = numericupdown2.Value;
如果您一心想要使用文本框,那么您需要删除空格 .Trim()
Quantity = Convert.ToInt32(txt_quantity.Text.Trim());
并int.TryParse改为使用;
int value = 0;
if (int.TryParse(txt_quantity.Text.Trim(), out value)
{
// Successful conversion so value now contains your integer
}
你可以对小数做同样的事情。
- 1 回答
- 0 关注
- 1064 浏览
添加回答
举报
0/150
提交
取消