在我的Windows应用程序“ Purchase Order Datagridview”中,如下所示
如果用户在当前行的数量单元格中未输入数字值,则会引发异常。我想知道如果我在此错误消息中按ok按钮后如何继续操作。我尝试了以下代码。但是它将持续弹出此消息。如何解决此问题。
private void dataGridView1_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
double unitPrice = 0;
int quantity = 0;
quantity = Convert.ToInt32(row.Cells[dataGridView1.Columns[2].Index].Value);
unitPrice = Convert.ToDouble(row.Cells[dataGridView1.Columns[3].Index].Value);
row.Cells[dataGridView1.Columns[4].Index].Value = quantity * unitPrice;
}
}
catch (Exception ex)
{
MessageBox.Show(" Error " + ex.Message);
dataGridView1.CurrentRow.Cells[2].Value = DBNull.Value;
}
}
答案 0 :(得分:0)
请参阅this.use int.TryParse
private void dataGridView1_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
double unitPrice = 0;
int quantity = 0;
int.TryParse(row.Cells[dataGridView1.Columns["Enter Your Column Name here"].Index].Value, out quantity))
if(!(quantity > 0))
{
MessageBox.Show(" Error ");
return;
}
unitPrice = Convert.ToDouble(row.Cells[dataGridView1.Columns["Enter Your Column Name here"].Index].Value);
row.Cells[dataGridView1.Columns["Enter Your Column Name here"].Index].Value = quantity * unitPrice;
}
}
catch (Exception ex)
{
}
}
完整示例以了解Tryparse:-
class Program
{
static void Main(string[] args)
{
string abc = "10abc";
int result = 0;
int.TryParse(abc, out result);
Console.WriteLine(result);
Console.ReadKey();
}
}
我如何测试:-
class Program
{
static void Main(string[] args)
{
string abc = "10abc";
int result = 0;
int.TryParse(abc, out result);
if(!(result>0))
{
Console.Write("Enter Numeric Value");
}
Console.ReadKey();
}
}