我想在数量和价格值之间执行乘法时检查网格列中的值。我做到了这一点,它完美无缺!
但是当我在列数量中输入字符串值或者在编辑列并将其留空之后,我遇到了问题。我收到一个错误:
那么我如何检查这些值以及当用户输入字符串,字符或空白输入时,显示带有反馈的MessageBox
?
这是我的代码:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int price, quantity, total;
quantity= int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString());
cena = int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Price"].Value.ToString());
total = quantity * price ;
dataGridView1.Rows[e.RowIndex].Cells["Total"].Value = total;
}
当我输入一个整数时,一切正常......
答案 0 :(得分:0)
尝试此操作,如果输入无法转换为int,则指定一些值。
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int price, quantity, total;
if(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value != null)
{
if(!int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString(), out quantity))
{
quantity= 0;
}
}else
{
quantity= 0;
}
price = int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Price"].Value.ToString());
total = quantity * price ;
dataGridView1.Rows[e.RowIndex].Cells["Total"].Value = total;
}
答案 1 :(得分:0)
使用try ... catch块代码
.cancelButton
你可以做可空类型
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e){
int price, quantity, total;
try {
quantity= int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString());
cena = int.Parse(dataGridView1.Rows[e.RowIndex].Cells["Price"].Value.ToString());
total = quantity * price ;
dataGridView1.Rows[e.RowIndex].Cells["Total"].Value = total;
} catch(NullReferenceException) { ... }
}
在这里阅读
https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx