I think I would have structured that class a little differently, but I agree with BC that the code you posted doesn't look like it should get into a loop. Here's another suggestion:
DataClass.DeleteRole:
public bool DeleteRole(int id, ref string Message)
{
bool IsOK = true;
try
{
command.Parameters.Add(new SqlParameter("@ID", id));
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "RolesDelete";
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
catch (SqlException ex)
{
IsOK = false;
if(ex.Number == 547)
Message = "Constraints error";
else
Message = ex.Message;
}
return IsOK;
}
RolesClass which calls DataClass.DeleteRole
private void deleteBut_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete this item?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
DataClass dc = new DataClass();
string Message = "";
if (dc.DeleteRole(int.Parse(this.grid.CurrentRow.Cells["ID"].Value.ToString()), ref Message))
dc.RefreshRoles();
else
MessageBox.Show(Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The point of this refactoring is that now, the Form doesn't know anything about where/how the data is being processed (previously, you had it catching a SqlException ... I don't believe that the Form should know anything at all about the database). This refactored codeis a little cleaner, I think.
~~Bonnie Berent [C# MVP]