存储过程不成功插入消息显示

时间:2014-11-07 05:16:22

标签: c# stored-procedures

我写了以下代码。我需要检查插入不成功。即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";
}

1 个答案:

答案 0 :(得分:1)

如果不成功,ExecuteNonQuery通常会抛出异常 - 请看一下:

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");
}