ASP.NET Update GridView statement
-
26-10-2019 - |
Question
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.
OTHER TIPS
Underneath the GridView there is the table needs to have at least one Unique ID in order to update a record. If you need to edit the UserID, you need to have a fixed key in your table. At least name it as UserKey. I think GridView could only edit and update data as long as you have a pointer to that row. Otherwise, remove the UserID from the DataKeyNames collection and assign it with the columns you think are unique and does not change.