Setting Up the DataGrid and Adding Edit / Delete Buttons
First, open Visual Studio and drop a DataGrid control onto the WebForm. The designer shows a tabular view that looks like a spreadsheet; it already includes a default set of columns that will be bound to the data source you supply. Most of the properties you’ll tweak are accessible through the Properties window, but a few key attributes require hand‑editing in the source view to give you full control.
You’ll want the grid to handle multiple reference tables – for instance, Customer, Product, and Order tables – and to show an Edit and Delete button in each row. To do that, add a TemplateColumn to the Columns collection and place a <asp:LinkButton> inside it for each action. The designer can insert the column, but you’ll still need to copy the markup into the source view to specify the CommandName and CommandArgument that the grid will use when a button is pressed. The final markup for the column looks like this:
The CommandName values are arbitrary but should match what you handle in the ItemCommand event. The CommandArgument pulls the primary key from the data row so the code behind can identify which record to edit or delete.
Next, wire up two event handlers that the grid will fire when the user interacts with it. The OnPageIndexChanged attribute tells the grid to invoke a method when pagination buttons are clicked, while OnItemCommand captures any button clicks within the grid rows. Place these attributes directly on the <asp:DataGrid> tag:
With these handlers defined, the grid is ready to talk to your server‑side logic.
In the code‑behind, the first thing you’ll do on page load is decide which table the grid should display. A common pattern is to read a query string or a session variable that tells the page which table to target, then store that value for use in the binding routine. For example:
Once the table name is stored, the BindDataGrid method pulls data from the correct database view or stored procedure. Because the SQL changes depending on the table, the method contains a simple switch statement that builds the query string accordingly:
The helper GetDataTableFromDatabase is a thin wrapper around ADO.NET that opens a connection, executes the query, and fills a DataTable. By separating the data‑retrieval logic from the grid configuration, the page remains clean and easy to extend for additional tables.
Finally, remember to set the AllowPaging property to true in the designer or in code if you want the grid to provide Next/Previous controls. The grid automatically creates a pager row at the bottom once paging is enabled, and the OnPageIndexChanged event will be triggered when the user navigates.
This section covered everything you need to place a DataGrid on a page, add per‑row edit and delete actions, and program the grid to fetch data from different tables. The next step is to handle the paging events and button clicks in the code behind.
Handling Paging and Row Commands in the DataGrid
After the DataGrid has been configured to display rows and show Edit and Delete links, the next critical piece is responding to user interactions. The grid’s OnPageIndexChanged event fires whenever the user clicks the Next or Previous buttons that appear in the pager row. In the handler, you simply set the new page index and rebind the data. The method is straightforward:
Because the grid already remembers the current page index, setting the CurrentPageIndex property updates the internal state. After assigning the new index, calling BindDataGrid forces the grid to refresh its display. This keeps the paging logic completely independent of the rest of the application.
The OnItemCommand event is where the magic happens for the Edit and Delete links. Each link you added earlier in the template column had a CommandName and a CommandArgument. When a user clicks one of these links, the grid raises myDataGrid_ItemCommand and passes an DataGridCommandEventArgs object that contains the command name, the source button, and the command argument. Inside the handler you first check the CommandName to determine which action the user requested, then you extract the row identifier from the CommandArgument:
The EditRecord and DeleteRecord methods are where you implement the business logic for each action. Notice that the handler is agnostic to the underlying database table; the rowId is passed straight through, and the specific table context is stored in the Session variable set earlier in Page_Load. That way, the same handler works for any reference table the page is showing.
When you need to edit a record, you typically want to redirect the user to a detail form that contains all fields for the chosen table. The EditRecord method handles that by building a URL that points to the detail page, attaching the rowId and the current table name as query string parameters. A simple implementation looks like this:
The detail form can read these parameters on its own Page_Load and query the database for the specific row, then populate the fields for the user to edit. Because the URL carries the primary key, the form knows exactly which record to display.
The DeleteRecord method, while not shown here, follows a similar pattern. It would call a stored procedure or execute a SQL delete command that uses the primary key and the table name. After deletion, you would call BindDataGrid again to refresh the grid and remove the deleted row from the display.
This section covers the core event handling logic that connects user actions in the DataGrid to the backend operations. By keeping the logic for paging and command processing in isolated methods, you make the code easier to maintain and extend for additional tables or actions. The final step is to look at how the detail form consumes the rowId and table name and populates its fields from the database.
Populating the Detail Form from the Selected Row
When the user clicks the Edit link in a DataGrid row, the browser is sent to a detail page that is tailored to the type of record the grid was showing. The URL the handler built contains two query string variables: table and id. On the detail page, you can read these values to determine both the table that holds the record and the primary key that identifies the row to edit. The pattern is simple and works for any of the reference tables the grid might display.
The first thing the detail form does on Page_Load is verify that it is not a postback. If it is the first time the page is being loaded, it retrieves the table name and the record id:
Dim recordId As Integer = Convert.ToInt32(Request.QueryString("id"))
LoadRecord(tableName, recordId)
End If
End Sub
The LoadRecord method builds a SQL query that selects every column from the appropriate view or table. Because the columns differ from table to table, the method uses a switch statement to create the correct SELECT statement. For example:
The helper method GetDataTableFromDatabase executes the query with a parameterized command to protect against SQL injection. Once the DataTable is returned, the PopulateFormFields method assigns each column value to the corresponding control on the form – TextBoxes, DropDownLists, or Labels. Because the DataTable contains only one row, you can simply reference dt.Rows(0):
The form’s Save button would then collect the values from the controls and build an UPDATE statement that writes back to the same table. Because you already know the table name and the primary key, the update can be performed in a single method that uses a switch statement similar to the one used in Keeping the data‑access logic in separate helper methods makes the code cleaner and allows you to swap out the database layer if needed. If you later decide to use Entity Framework or Dapper instead of raw ADO.NET, only the When the user finishes editing and clicks Save, the form can redirect back to the original grid page with the same This final part ties everything together: selecting a row in the DataGrid sends the user to a detail page that knows which table the row belongs to and which record to load. By using a consistent pattern for retrieving and updating data, the code stays flexible and can be extended to new tables without rewriting the entire logic. The result is a responsive interface where clicking Edit on any row opens a fully populated form ready for editing. Ready to build a multi‑table DataGrid that opens detail forms on edit? Start by copying the code snippets above into your own project and tweak the SQL to match your database schema. If you need additional guidance, feel free to check out Roger McCook’s website for more tips on ASP.NET development. And don’t forget to subscribe to
LoadRecord
GetDataTableFromDatabase routine needs to change.table parameter, preserving the context. Because the grid reloads on every initial request, the user will see the updated values immediately. If you prefer a smoother user experience, you can also use AJAX to submit the form without a full page reload, but the basic flow remains the same.
Tags





No comments yet. Be the first to comment!