简体   繁体   中英

Error message for data duplication in asp.net

I have tried this below code, but it throws a unique key constraint error. I would like it as a pop-up message; see my below code.

using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
    var fromdate = DateTime.Parse(txtfromdate.Text);
    var todate = DateTime.Parse(txttodate.Text);
    var datedif1 = (todate - fromdate).Days;

    var sqlInsert = new SqlCommand("INSERT INTO datelist ([datedif],[batch],[daywk],[semester],[weekbatch],[subject],[facultyname],[facultyid],[WeekMonth])  VALUES  (@datedif,@batch,@daywk,@semester,@weekbatch,@subject,@facultyname,@facultyid,@weekMonth)", con2);
    var sqlParamater = sqlInsert.Parameters.Add("@datedif", SqlDbType.Date);
    var sqlParameter1 = sqlInsert.Parameters.Add("@batch", SqlDbType.NVarChar);
    var sqlParameter2 = sqlInsert.Parameters.Add("@daywk", SqlDbType.NVarChar);
    var sqlParameter3 = sqlInsert.Parameters.Add("@semester", SqlDbType.NVarChar);
    var sqlParameter4 = sqlInsert.Parameters.Add("@weekbatch", SqlDbType.NVarChar);
    var sqlParameter5 = sqlInsert.Parameters.Add("@subject", SqlDbType.NVarChar);
    var sqlParameter6 = sqlInsert.Parameters.Add("@facultyname", SqlDbType.NVarChar);
    var sqlParameter7 = sqlInsert.Parameters.Add("@facultyid", SqlDbType.NVarChar);
    var sqlParameter8 = sqlInsert.Parameters.Add("@WeekMonth", SqlDbType.NVarChar);

    con2.Open();
    try
    { 
        for (var i = 0; i <= datedif1; i++)
        {
            var consecutiveDate = fromdate.AddDays(i);

            sqlParamater.Value = consecutiveDate;
            sqlParameter1.Value = batch1;
            sqlParameter2.Value = dayweek;
            sqlParameter3.Value = semester;
            sqlParameter4.Value = weekbatch;
            sqlParameter5.Value = subject;
            sqlParameter6.Value = faculty;
            sqlParameter7.Value = facultyid;
            sqlParameter8.Value = weekmonth;

            int s = sqlInsert.ExecuteNonQuery();
        }
        con2.Close();
    }
    catch(ConstraintException ex)
    {
        throw new ApplicationException("data are duplicated");
    }
}

Here's a screen shot of the error which am getting,

You are catching a ConstraintException , but the insert is throwing a SqlException which is not a subclass of ConstraintException . Change the catch and you will get it handled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM