The idea is that we have a DataGrid which has list of records in a database table. We want to be able to select a row and call up a detail form which will have the corresponding database detail.
Using Visual Studio .NET, I drag and drop a DataGrid onto my web form and start tinkering with the properties. This is the way I like to do it but I still have to switch to HTML view and code a few items by hand. Here is some actual code from a recent project I worked on for a large company in Atlanta. The grid is generalized to handle several different reference tables in the database. The detail form that will be called is dependent on which table I’m working with.
Most of the code was generated automatically by Visual Studio but I had to switch to HTML view and add a couple of lines myself. The following info was manually entered:
This following line (from above) calls a procedure named “myDataGrid_PageChanger” when I want to move forward or backward a page.
OnPageIndexChanged=”myDataGrid_PageChanger”
These following lines (from above) put an EDIT button and a DELETE button in each row.
This following line (from above) calls a procedure named “myDataGrid_ItemCommand
” when one of the above buttons is clicked.
OnItemCommand="myDataGrid_ItemCommand"
The following code is entered in the code-behind page in the page_load procedure. This is where I determine which table I’m working with and refresh the DataGrid accordingly. :
The following procedure is entered in the code-behind file to refresh the DataGrid. Note how the SQL syntax changes depending on which table I’m working with.
The following procedure is called when you move forward or backward a page.
The following procedure is called when you click one of the command buttons in the DataGrid. Notice how I determine which button was clicked and how I pick out the Row_ID that I want to edit or delete.
Finally, there is one more procedure I’ll show which is the EditRecord procedure. I’m not showing the DeleteRecord procedure because it is not relevant to this article. This is the code that redirects you to the appropriate detail form. By passing the database row in the call, you can write code in the detail form to fill the form from the database.
Conclusion
I’ve demonstrated how we can have a form with a DataGrid control which can be used generically for several database tables. The control will contain an EDIT button in each row. When you click the EDIT button, the program selects the appropriate detail form and opens it (passing in the row_id so that the detail form can be populated from the database.)
Click here to sign up for FREE tech newsletters from Murdok!
Visit Roger McCook’s Web site at http://www.mccooksoftware.com.