Search code examples
c#sqlconnectioncslaexecutereader

How to capture duplicate values and show message box while reading from database?


I've a DataGrid which uses a list object. I would like to prevent users from entering duplicate values into database.

My stored procedure already prevents duplicate data from entering into database but I would like to show a more descriptive message to the users explaining they can't enter duplicate values.

Below is my code where I'm inserting values via Stored Procedure:

using (var cn = ConnectionManager<SqlConnection>.GetManager(Database))
            using (var cmd = new SqlCommand("Save", cn.Connection))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@TableId", ReadProperty(TableIdProperty));
                cmd.Parameters.AddWithValue("@Q1", ReadProperty(Q1Property).ToUpper());
                cmd.Parameters.AddWithValue("@Q2", ReadProperty(Q2Property));

                using (var dr = new SafeDataReader(cmd.ExecuteReader()))
                {
                    //Would like to capture duplicates here if a record already exists with same Q1 and Q2 values 
                    if (dr.Read())
                        LoadProperties(dr);
                    else
                        dr.NextResult(); // sproc error happens here
                }
            }

Solution

  • If I got it right you have an Application where users can Insert new rows and you want to prevent duplicated entries.

    If this is right you could add a Database Function that returns an ErrorCode and you could call this function using SqlCommand from your code.