C# – GridView doesn’t report an exception

ado.netasp.netcgridviewsql server

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.

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();

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

thanx

EDIT:

Hello,

Sorry for not replying sooner, but I haven't noticed I got a reply.

Anyways, for some reason it's working now, meaning GridView does report an exception. Thus I must've made some mistake in my code, but due to constant rewriting of my code I have no idea where would that mistake be. Sorry for wasting your time and thank you for helping me out

Best Answer

Looking at the error and your code. It appears to be a SQL Database Error and not an issue with the GridView.

SQL does not allow updates to IDENTITY columns since they get generated by the database engine. In this case "EmployeeId" is such a field.