Design of SQL Table Users:
Columns:
ID(Primary Key),
Name,
Age,
Zip.
I am displaying a grid view onto the asp.net application with the above table details which i am able to do now.Right now i am displaying only Name,age,zip on to the gridview.There is a form below the gridview where user can enter the data and save back to the DB.Here i am able to enter name,age,zip to the database and i am able to see the changes in the gridview.
So when i enter a duplicate name its not saving to the database as expected,at this point i have to show some thing to the user that the name already exists .
Here is my code in c#:
try
{
param[0] = new SqlParameter("@Name", SqlDbType.NVarChar);
param[0].Value = txtName.Text;
param[1] = new SqlParameter("@Age", SqlDbType.NVarChar);
param[1].Value = txtAge.Text;
param[2] = new SqlParameter("@Zip", SqlDbType.int);
param[2].Value = txtZip.Text;
DBHelper helper = new DBHelper();
helper.ExecuteNonQuery(CommandType.StoredProcedure, "Add_Users", param);
GridView1.DataBind();
}
catch (Exception ex)
{
}
I am expecting an sql exception in the above code where i am planning to notify the user .But i am unable to get any exception .
Can some one suggest where i am missing the catch here.
I just want to notify the user that the name is already taken eventually.
Using exceptions is a bad design in this case. This is not an error, but a predictable behaviour of your program.
One of the easiest ways to solve the problem is doing a select at the end of the Add_Users stored procedure that returns 1 or 0, depending on the success or failure, and using ExecuteScalar insead of ExecuteNonQuery to get the result.
You can also use a return in the stored procedure, and take back that value (geenrally as a special output parameter), but I don’t know if the DbHelper allows you to do so.