views:

163

answers:

2

Hello,

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


+2  A: 

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.

Jose Basilio
I came here to say this..+1
Meff
But why did above code, which executed the same update statement as GridView, report an SqlException, but Gridview didn't?
SourceC
It appears that the GridView control swallows the Exception unless you set the property-> EnableModelValidation="true"
Jose Basilio
A: 

I the same kind of problem: I caught the exception in the object datasource's Selecting handler, but forgot to set the exception as handled: e.ExceptionHandled = true. The page rendered without my error message on the page, like if no error happened. With e.ExceptionHandled = true, everything was fine.

devMomentum