WinForms DataGridView: row selection, parameterized SQL and safe updates
A hands-on retrospective explaining how a WinForms grid should identify records and save changes safely.
Sample period date: Oct 15, 2013. These essays revisit earlier technologies from today's editorial perspective; they are not represented as posts originally published in those years.
A visual row is not a database record
The third visible row in a DataGridView is not necessarily the third record in the database. Sorting or filtering changes positions. A safe update requires a stable primary key stored with each record. If the save operation uses a row number rather than record identity, the wrong customer or product may be modified. Carry the identifier with the bound data.
Never build SQL by concatenating input
Appending TextBox values directly to SQL causes quoting bugs and opens the door to SQL injection. Use parameters instead; on SQL Server, SqlCommand with explicitly typed parameters is a clear starting point. Restrict updates by a stable record key and inspect the affected-row count. A button click that appears successful does not prove that the intended record was saved.
A failed write must remain visible
When a cell changes visually but the database update fails, the user can wrongly assume that the data was saved. Refresh the bound data after confirming success; if the write fails, preserve the user's selection and show an actionable error. Close connections deterministically and keep long-running database operations away from the UI thread.
Verification checklist
Confirm that the primary key remains correct after sorting. Test null values, Unicode names, quotes, network failures and concurrent edits. Finally, verify that saving the same record twice does not create duplicates. These checks apply to legacy WinForms and to modern editing interfaces alike.
Comments
0 real commentsNo real reader comments yet.
✎ Write a comment