C# 存储过程未成功插入消息显示

C# 存储过程未成功插入消息显示,c#,stored-procedures,C#,Stored Procedures,我编写了以下代码。我需要检查插入是否失败。i、 ecmd.ExecuteNonQuery()!=1因为我想显示该错误情况的消息。你有什么建议吗 if (cmd.ExecuteNonQuery() == 1) { lblInserted.Text = "Inserted:" + count; // MessageBox.Show("Inserted"); lblInserted.Font = new System.Drawing.Font(lblInserted.Font,

我编写了以下代码。我需要检查插入是否失败。i、 e
cmd.ExecuteNonQuery()!=1
因为我想显示该错误情况的消息。你有什么建议吗

if (cmd.ExecuteNonQuery() == 1)
{
    lblInserted.Text = "Inserted:" + count;
    // MessageBox.Show("Inserted");
    lblInserted.Font = new System.Drawing.Font(lblInserted.Font, FontStyle.Bold);
    lblInserted.ForeColor = System.Drawing.Color.Green;
    count++;
    dataGridViewDisplayPanel.Rows[i].Cells[nextCell - 1].Style.BackColor = Color.Green;
    dataGridViewDisplayPanel.Rows[i].Cells[nextCell - 1].Value = "Inserted Successfully";
}

通常,如果执行不成功,ExecuteOnQuery会引发异常-请查看以下内容:

try
{
    // run the query
    cmd.ExecuteNonQuery();
    lblInserted.Text = "Inserted:" + count;
    // MessageBox.Show("Inserted");
    lblInserted.Font = new System.Drawing.Font(lblInserted.Font, FontStyle.Bold);
    lblInserted.ForeColor = System.Drawing.Color.Green;
    count++;
    dataGridViewDisplayPanel.Rows[i].Cells[nextCell - 1].Style.BackColor = Color.Green;
    dataGridViewDisplayPanel.Rows[i].Cells[nextCell - 1].Value = "Inserted Successfully";
}
catch (Exception ee9)
{
    // Deal with the error
    MessageBox.Show("Oops, it failed");
}

此外,如果没有插入行,ExecuteOnQuery()将返回0。但这不是一个好主意使用=1,因为可以插入多行。所以使用=0如果您需要捕获异常,也可以使用下面答案中的try-catch。