Search code examples
c#asp.netgridviewupdatecommand

ASP.NET Update GridView statement


I am using VS2005 C# and SQL Server 2005.

I have a GridView and this is my current Update statement:

UpdateCommand="UPDATE [UserData] SET [UserID] = @UserIDe, [Username] = @Username, [Age] = @Age, [MemberType]=@MemberType WHERE [UserID] = @UserID

The above statement will update the user row identify by UserID.

However, I would like the variable UserID to be editable, thus if I edit my UserID while updating the table, the row will not be updated because that particular UserID may not exist.

How can I use the UpdateCommand and update the row by identifying the row number of the edited row?


Solution

  • This can be done by tracking all of the original values. Visual Studio will do this for you if you use the wizard to generate your SQL statements, and you select the "use optimistic concurrency" option as shown here.

    An example of the generated SQL can be found here.

    Code sample from the page:

    UPDATE Products SET
        ProductName = @ProductName,
        UnitPrice = @UnitPrice
    WHERE
        ProductID = @original_ProductID AND
        ProductName = @original_ProductName AND
        UnitPrice = @original_UnitPrice
    

    Reading through the article, you should be able to apply the same type of query to your situation, as using the original values should allow you to bypass the need for a primary key. However, I should point out that having an editable identification key is a very bad design, as you can't guarantee it is unique. you can very easily end updating more than one record, along with a whole host of other issues.