Building a DataGrid Helper Control for ASP.NET 1.x: Part 2
2004-09-13 12:47
489 查看
[Download Code]
In Part 1 of this series, we built a DataGrid helper control that would drastically simplify the programming of a read-only data access page. In Part 2, we continue our quest to enhance the control and use it to simplify the programming of a data access page with update and delete capability. We will push the idea to the extreme and show that we can also develop a data access page with sorting, paging, deleting and updating capabilities without writing a single line of code in ASP.NET 1.x, just like ASP.NET 2.0 has promised.
Again, we will start by examining a typical data access page with update and delete capability and identify repetitive code that can be moved into our control. We will then enhance the DataGridHelper control to handle update and delete. We will show how to use the control and conclude the article.
Now, let us take a look of a typical data access page first.
In Part 1 of this series, we built a DataGrid helper control that would drastically simplify the programming of a read-only data access page. In Part 2, we continue our quest to enhance the control and use it to simplify the programming of a data access page with update and delete capability. We will push the idea to the extreme and show that we can also develop a data access page with sorting, paging, deleting and updating capabilities without writing a single line of code in ASP.NET 1.x, just like ASP.NET 2.0 has promised.
Again, we will start by examining a typical data access page with update and delete capability and identify repetitive code that can be moved into our control. We will then enhance the DataGridHelper control to handle update and delete. We will show how to use the control and conclude the article.
Now, let us take a look of a typical data access page first.
A Typical Data Access Page with Update and Delete Capability | ||||||||||||||||||||||||||||||||||||||
[Download Code] We will first look at what is involved in creating a typical data access page with update and delete functionality by examining an example. A live demo can be found at http://www.dotneteer.com/projects/DataGridHelper/v2/TypicalDataAccessPage.aspx. The page is an enhancement over the same page demonstrated in the first part of this article. I made the following enhancements: 1. Add a button column for the Edit/Update/Cancel commands. Add another button column for the Delete command. 2. Set the AutoGenerateColumns property to false. Instead of letting the DataGrid control to generate the columns automatically, I added some bound columns to the DataGrid control at design time. This allows us to have finer control over the behavior of the DataGrid, such as setting user-friendly headers, the format for the data displayed, as well as the sort expression. More importantly, we can now make some columns read-only--we do not want users to edit an identity column. 3. Set the DataKeyField property to the name of the primary key column of the table we are going to edit. The DataGrid control will then provide the value of the primary key through the DataKeys property at run-time, so we can use it to update and delete a record. 4. Add code to handle the EditCommand, CancelCommand, UpdateCommand and DeleteCommand events of the DataGrid. The SqlDataAdapter member in the page was configured using the "Data Adapter Configuration Wizard." Using "advanced options," we turned off the "Use optimistic concurrency" and "Refresh dataset" options because we do not use them. The code that handles the EditCommand and CancelCommand events is essentially repetitive, as shown below: private void dataGridProducts_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { dataGridProducts.EditItemIndex = e.Item.ItemIndex; bindGrid(); } private void dataGridProducts_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { dataGridProducts.EditItemIndex = -1; bindGrid(); } We can easily move this code to the DataGridHelper control using the same technique used in Part 1 of this series. Now let us take a look of the code that handles the DeleteCommand event: private void dataGridProducts_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { SqlCommand cmd = sqlDataAdapterProducts.DeleteCommand; Object key = dataGridProducts.DataKeys[e.Item.ItemIndex]; try { cmd.Parameters["@ProductId"].Value = key; sqlConnection.Open(); cmd.ExecuteNonQuery(); lblMsg.Text = "Product " + key.ToString() + " successfully deleted."; bindGrid(); } catch (Exception ex) { lblMsg.Text = "Failed to delete Product " + key.ToString() + "due to following error:<BR>" + ex.ToString(); } } This code basically retrieves the value of primary key column from the DataKeys property of the DataGrid control and sets it to the parameters of the delete command and then executes the command. At last, let us take a look of the code that handles the UpdateCommand event: private void dataGridProducts_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { SqlCommand cmd = sqlDataAdapterProducts.UpdateCommand; Object key = dataGridProducts.DataKeys[e.Item.ItemIndex]; try { cmd.Parameters["@Original_ProductId"].Value = key; String[] cols = {"@Original_ProductId","@ProductName", "@SupplierID", "@CategoryID", "@QuantityPerUnit", "@UnitPrice", "@UnitsInStock", "@UnitsOnOrder", "@ReorderLevel", "@Discontinued"}; int numCols = e.Item.Cells.Count; for (int i=3; i<numCols; i++) //skip first, second, third and last column { String colvalue =((System.Web.UI.WebControls.TextBox) e.Item.Cells[i].Controls[0]).Text; cmd.Parameters[cols[i-2]].Value = colvalue; } sqlConnection.Open(); cmd.ExecuteNonQuery(); lblMsg.Text = "Product " + key.ToString() + " successfully updated."; dataGridProducts.EditItemIndex = -1; bindGrid(); } catch (Exception ex) { lblMsg.Text = "Failed to update Product " + key.ToString() + "due to following error:<BR>" + ex.ToString(); } } The code for the UpdateCommand event was borrowed from the ASP.NET QuickStart tutorial. It is no doubt the ugliest part of DataGrid programming. The first part of the task is to locate the table cell that corresponds to the database table column of interest. Once the cell is located, we need to find the control in the cell that was used for data input. We can find the control by either looping through the Controls collection or using the FindControl method. We can then update the database using the retrieved values.
|
相关文章推荐
- Building a DataGrid Helper Control For ASP.NET 1.x: Part 1
- Building a DataGrid Helper Control for ASP.NET 1.x: Part 3
- Google Maps Control for ASP.Net - Part 2 (转载)
- Server-side ASP .NET Data Binding, Part 2: Customizing the DataGrid Control
- Multiple Column Dropdownlist for the ASP.NET DataGrid
- Setting Expires and Cache-Control: max-age headers for static resources in ASP.NET
- PagerHelper for ASP.NET MVC3
- jQuery EasyUI DataGrid 分页 FOR ASP.NET
- 【翻译】Building a Simple Blog Engine with ASP.NET MVC and LINQ - Part 3
- RadControl For Asp.net的官方API
- Pager Control for ASP.NET(asp.net分页控件例子)
- 以服务器端为中心的 ASP.NET AJAX 模式 (Part 2 - Control)
- Asp.net 控件(2)-CSS Control Adapter Toolkit for ASP.NET 2.0 (转载)
- 以服务器端为中心的 ASP.NET AJAX 模式 (Part 2 - Control)
- Atlas Control Toolkit and Source Code for the Build-in Asp.Net 2.0 Providers
- Building Custom Providers for ASP.NET 2.0 Membership
- [收藏]The Baker's Dozen: 13 Tips for Building Database Web Applications Using ASP.NET 3.5, LINQ, and SQL Server 2005 Reporting Services
- 交互式日历日程控件Scheduling Control for ASP.NET
- Asp.net DataGrid control with Fixed Header and Scrollbar
- Custom TabControl for asp.net page