C# – If Sql Server returns an error, then SqlException should be thrown. But it isn’t

ado.netasp.netcgridview

If I bind GridView to SqlDataSource and also set AutoGenerateEditButton to true, and if I then try to update a field ( this field being a primary key in database ), then database should return an error and thus SqlException should be thrown?!
So why doesn’t page report an exception? Instead, all Gridview does is setting all fields in that row back to their original values.

thanx

EDIT:

Hello,

When I executed same update statement with the following code, I got Cannot update identity column 'EmployeeID' exception, so I’m assuming Sql Server did report same error when GridView tried to update, but for some reason exception wasn't raised:

        SqlConnection sc = new SqlConnection();
        sc.ConnectionString = @"Data source=localhost; integrated security=sspi; initial catalog=northwind;";
        SqlCommand sComand = new SqlCommand();

        sComand.Connection = sc;
        sComand.CommandText = "update Employees set EmployeeId=100,FirstName='Suzy',"+ 
                   "LastName='Smile',City='Moon' where EmployeeId=1";
        sc.Open();
        int I = sComand.ExecuteNonQuery();

SECOND EDIT:

Is your DataKeyNames property set correctly?

I tried with setting DataKeyNames="EmployeeId", but exception was still not raised

Best Answer

If your SQL query returns a result, then C# will get that result. If your SQL query throws an exception, then C# will get that exception. You cannot mix and match here, it's not a wardrobe.

Related Topic