在下面的代碼中,我正在嘗試驗證文本框(txt_quantity 和 txt_discount)但是MessageBox.Show("Cannot be empty");我沒有得到這個,而是得到了錯誤('輸入字符串的格式不正確。')我在這里忘記了什么嗎?txt_數(shù)量(整數(shù))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條經(jīng)驗 獲得超7個贊
使用 NumericUpDown 而不是文本框來捕獲整數(shù)/十進制值。它為您處理所有驗證,以阻止用戶輸入非數(shù)字值。您可以設(shè)置所需的最大值和最小值,并且不必擔(dān)心沒有輸入任何值,因為 NumericUpDown 將始終具有默認值。
如果您使用整數(shù),則只需在檢索值時轉(zhuǎn)換為 int,否則返回小數(shù)。所以你的代碼是:
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
}
你可以對小數(shù)做同樣的事情。
- 1 回答
- 0 關(guān)注
- 1118 瀏覽
添加回答
舉報
0/150
提交
取消