Now it's time to investigate some of the more complex beasts that ASP.NET has to offer for displaying list and bound tabular data. The DataList and DataGrid offer a lot more structure for the data that is bound to them. They also offer tons of control over how the data is displayed and what it can do with the addition of more powerful templates that handle column formatting and as well as function.
Because the DataList control has HTML formatting and additional function, it has a few more properties than the Repeater control.
Property | Description |
---|---|
AlternatingItemStyle | Gets the style properties for alternating items in the DataList control. |
EditItemIndex | Gets or sets the index number of the item selected for editing in the DataList control. |
EditItemStyle | Gets the style properties for the item selected for editing in the DataList control. |
ExtractTemplateRows | Gets or sets a value that indicates whether the rows of a Table control, defined in each template of a DataList control, are extracted and displayed. In other words, if you want to control the layout of each Repeater, insert an asp:table object into the ItemTemplate and set this to true. Then the data list will use the rows and layout from the table object rather than the DataList itself. |
FooterStyle | Gets the style properties of the footer section in the DataGrid control. |
GridLines | Gets or sets what the style of the gridline are for the DataList control when the RepeatLayout property is set to RepeatLayout.Table. |
HeaderStyle | Gets the style properties for the heading section of the DataList control. |
Items | Gets a collection of DataListItem objects representing the individual items within the control. |
ItemStyle | Gets the style properties for the items in the DataList control. |
RepeatColumns | Gets or sets the number of columns to display in the DataList control. |
RepeatDirection | Gets or sets whether the DataList control displays vertically or horizontally. |
RepeatLayout | Gets or sets whether the control is displayed in a table or flow layout. |
SelectedIndex | Gets or sets the index of the selected item in the DataList control. |
SelectedItem | Gets the selected item in the DataList control. |
SelectedItemStyle | Gets the style properties for the selected item in the DataList control. |
SeparatorStyle | Gets the style properties of the separator between each item in the DataList control. |
ShowFooter | Gets or sets a value indicating whether the footer section is displayed in the DataList control. |
ShowHeader | Gets or sets a value indicating whether the header section is displayed in the DataList control. |
The DataList possesses all the templates that the Repeater has (see Table 9.9), plus one additional template called the EditItemTemplate, which is used to control the layout and function of an item that has been selected for editing.
Template | Description |
---|---|
HeaderTemplate | If specified, rendered one time before anything in any of the other templates. |
ItemTemplate | Required; renders once for each item within the bound data source. |
EditItemTemplate | If specified, renders for the item selected for editing in the DataList control. |
AlternatingItemTemplate | If specified, rendered alternately with ItemTemplate through the items within the bound data source. |
SeparatorTemplate | If specified, renders between each item in the bound data source. |
FooterTemplate | If specified, renders once after all the items of the datasource have been rendered. |
As you can see, there are a whole bunch more toys to play with in the DataList. I could take up 20 pages just describing and giving examples of the forms and functions of the DataList, but I'm not going to do that. What I am going to show you is some of the power function of the DataList, including its capability to define the visual aspect of the data, as well as some functions of the DataList.
One of the functions I'd like to demonstrate is how to use the control to edit data directly. In the following example there is a whole heckuvalotta stuff going on, and again I stress that you should focus on the DataList control in this example. In a nutshell, this example builds a table of employee names, displays them in a DataList control, and enables the user to update and delete employees from the table.
<%@ page language="vb" runat="server"%> <%@ Import Namespace="System.Data" %> <script language="VB" runat="server"> Dim Employees As DataTable Dim EmployeesView As DataView Sub Page_Load(sender As Object, e As EventArgs) If Session("Employees") Is Nothing Then Employees = New DataTable() Employees.Columns.Add(New DataColumn("ID", GetType(String))) Employees.Columns.Add(New DataColumn("FirstName", GetType(String))) Employees.Columns.Add(New DataColumn("LastName", GetType(String))) Session("Employees") = Employees dim OurArray(,) as String = {{"1","Nancy","Davolio"},{"54","Andrew","Fuller"}, {"138","Janet","Leverling"}} dim i As Integer For i = 0 To 2 Dim dr As DataRow = Employees.NewRow() dr(0) = OurArray(i,0) dr(1) = OurArray(i,1) dr(2) = OurArray(i,2) Employees.Rows.Add(dr) Next i Else Employees = CType(Session("Employees"), DataTable) End If EmployeesView = New DataView(Employees) EmployeesView.Sort = "ID" If Not IsPostBack Then BindList() End If End Sub Sub BindList() OurDataList.DataSource = EmployeesView OurDataList.DataBind() End Sub Sub DataList_EditCommand(sender As Object, e As DataListCommandEventArgs) OurDataList.EditItemIndex = CInt(e.Item.ItemIndex) BindList() End Sub Sub DataList_CancelCommand(sender As Object, e As DataListCommandEventArgs) OurDataList.EditItemIndex = - 1 BindList() End Sub Sub DataList_DeleteCommand(sender As Object, e As DataListCommandEventArgs) Dim ID As String = CType(e.Item.FindControl("OurLabel"), Label).Text EmployeesView.RowFilter = "ID='" & ID & "'" If EmployeesView.Count > 0 Then EmployeesView.Delete(0) End If EmployeesView.RowFilter = "" OurDataList.EditItemIndex = - 1 BindList() End Sub Sub DataList_UpdateCommand(sender As Object, e As DataListCommandEventArgs) Dim ID As String = CType(e.Item.FindControl("OurLabel"), Label).Text Dim FirstName As String = CType(e.Item.FindControl("FirstNameText"), TextBox).Text Dim LastName As String = CType(e.Item.FindControl("LastNameText"), TextBox).Text EmployeesView.RowFilter = "ID='" & ID & "'" If EmployeesView.Count > 0 Then EmployeesView.Delete(0) End If EmployeesView.RowFilter = "" Dim dr As DataRow = Employees.NewRow() dr(0) = ID dr(1) = FirstName dr(2) = LastName Employees.Rows.Add(dr) OurDataList.EditItemIndex = - 1 BindList() End Sub </script> <html> <head> <title>Edit DataList</title> </head> <body> <form runat=server> <asp:DataList runat="server" BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="1" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" EditItemStyle-BackColor="#CCCCCC" OnEditCommand="DataList_EditCommand" OnUpdateCommand="DataList_UpdateCommand" OnDeleteCommand="DataList_DeleteCommand" OnCancelCommand="DataList_CancelCommand"> <HeaderTemplate><b>Employees</b></HeaderTemplate> <ItemTemplate> <u>ID:</u> <%# (CType(Container.DataItem, DataRowView))("ID")%><br> <u>Name:</u> <%# (CType(Container.DataItem, DataRowView))("FirstName")%> <%# (CType(Container.DataItem, DataRowView))("LastName")%><br> <asp:LinkButton Text="Edit" CommandName="edit" runat="server"/> </ItemTemplate> <EditItemTemplate> ID: <asp:Label Text='<%# (CType(Container.DataItem, DataRowView))("ID") %>' runat="server"/><br> FirstName: <asp:TextBox Text='<%# (CType(Container.DataItem, DataRowView))("FirstName") %>' Size="5" runat="server"/><br> LastName: <asp:TextBox Text='<%# DataBinder.Eval(Container.DataItem, "LastName") %>' Size="5" runat="server"/> <br> <asp:LinkButton Text="Update" CommandName="update" runat="server"/> <asp:LinkButton Text="Delete" CommandName="delete" runat="server"/> <asp:LinkButton Text="Cancel" CommandName="cancel" runat="server"/> </EditItemTemplate> </asp:DataList> </form> </body> </html>
<%@ page language="cs" runat="server"%> <%@ Import Namespace="System.Data" %> <script runat="server"> DataTable Employees; DataView EmployeesView; void Page_Load(Object sender, EventArgs e){ if (Session["Employees"] == null){ Employees = new DataTable(); Employees.Columns.Add(new DataColumn("ID", typeof(string))); Employees.Columns.Add(new DataColumn("FirstName", typeof(string))); Employees.Columns.Add(new DataColumn("LastName", typeof(string))); Session["Employees"] = Employees; String[,] OurArray = {{"1","Nancy","Davolio"},{"54","Andrew","Fuller"} ,{"138","Janet","Leverling"}}; for (int i = 0;i<=2;i++){ DataRow dr = Employees.NewRow(); dr[0] = OurArray[i,0]; dr[1] = OurArray[i,1]; dr[2] = OurArray[i,2]; Employees.Rows.Add(dr); } }else{ Employees = (DataTable)Session["Employees"]; } EmployeesView = new DataView(Employees); EmployeesView.Sort = "ID"; if (!IsPostBack){ BindList(); } } void BindList(){ OurDataList.DataSource = EmployeesView; OurDataList.DataBind(); } void DataList_EditCommand(Object sender,DataListCommandEventArgs e){ OurDataList.EditItemIndex = (int)e.Item.ItemIndex; BindList(); } void DataList_CancelCommand(Object sender,DataListCommandEventArgs e){ OurDataList.EditItemIndex = - 1; BindList(); } void DataList_DeleteCommand(Object sender,DataListCommandEventArgs e){ String ID = ((Label) e.Item.FindControl("OurLabel")).Text; EmployeesView.RowFilter = "ID='" + ID + "'"; if (EmployeesView.Count > 0){ EmployeesView.Delete(0); } EmployeesView.RowFilter = ""; OurDataList.EditItemIndex = - 1; BindList(); } void DataList_UpdateCommand(Object sender,DataListCommandEventArgs e){ String ID = ((Label)e.Item.FindControl("OurLabel")).Text; String FirstName = ((TextBox)e.Item.FindControl("FirstNameText")).Text; String LastName = ((TextBox)e.Item.FindControl("LastNameText")).Text; EmployeesView.RowFilter = "ID='" + ID + "'"; if (EmployeesView.Count > 0){ EmployeesView.Delete(0); } EmployeesView.RowFilter = ""; DataRow dr = Employees.NewRow(); dr[0] = ID; dr[1] = FirstName; dr[2] = LastName; Employees.Rows.Add(dr); OurDataList.EditItemIndex = - 1; BindList(); } </script> <html> <head> <title>Edit DataList</title> </head> <body> <form runat=server> <asp:DataList runat="server" BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="1" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" EditItemStyle-BackColor="#CCCCCC" OnEditCommand="DataList_EditCommand" OnUpdateCommand="DataList_UpdateCommand" OnDeleteCommand="DataList_DeleteCommand" OnCancelCommand="DataList_CancelCommand"> <HeaderTemplate><b>Employees</b></HeaderTemplate> <ItemTemplate> <u>ID:</u> <%# ((DataRowView)Container.DataItem)["ID"]%><br> <u>Name:</u> <%# ((DataRowView)Container.DataItem)["FirstName"]%> <%# ((DataRowView)Container.DataItem)["LastName"]%><br> <asp:LinkButton Text="Edit" CommandName="edit" runat="server"/> </ItemTemplate> <EditItemTemplate> ID: <asp:Label Text='<%# ((DataRowView)Container.DataItem)["ID"]%>' runat="server"/><br> FirstName: <asp:TextBox Text='<%# ((DataRowView)Container.DataItem)["FirstName"]%>' Size="5" runat="server"/><br> LastName: <asp:TextBox Text='<%# ((DataRowView)Container.DataItem)["LastName"]%>' Size="5" runat="server"/> <br> <asp:LinkButton Text="Update" CommandName="update" runat="server"/> <asp:LinkButton Text="Delete" CommandName="delete" runat="server"/> <asp:LinkButton Text="Cancel" CommandName="cancel" runat="server"/> </EditItemTemplate> </asp:DataList> </form> </body> </html>
As you can see in Figure 9.8, the DataList provides a powerful interface control for listing and editing data. After you move into the chapter on handling database and manipulating data, I will show you how to leverage these feature of the DataList and the DataGrid, for that matter.
The DataList basically provides one table cell per Item Row in the data source; the DataGrid provides a cell for each Item in the data source's row.
Let me be honest with you. It's currently 1:00 a.m. and looking at the DataGrid now is like looking at Mount Everest. The DataGrid is the granddaddy of all controls. This thing slices, dices, whips, purrees, chops, blends, and dices data-sources in just about every way that you can think.
If you want to display tabular data, this is it the be-all, end-all, you ain't gonna need anything else to do the job, control. You want properties, it's got properties. You want templates, it's got templates. I'd love to meet the guys who built this monster because it does it all.
Properties and methods and templates and their properties and methods and on and on and on. So buckle your seatbelts; I just got a fresh cup of coffee, we're going for a ride.
Table 9.10 lists the DataGrid object properties.
Property | Description |
---|---|
AllowCustomPaging | Gets or sets a Boolean value indicating whether custom paging is enabled. |
AllowPaging | Gets or sets a Boolean value indicating whether paging is enabled. |
AllowSorting | Gets or sets a Boolean value indicating whether sorting is enabled. |
AlternatingItemStyle | Gets the style properties for the alternating items in the DataGrid. |
AutoGenerateColumns | Gets or sets a Boolean value indicating whether BoundColumn objects are created automatically and displayed in the DataGrid for each field in the datasource. |
BackImageURL | Gets or sets the URL for the image that is to be displayed in the background of the DataGrid. |
Columns | Gets a collection of objects of the columns in the DataGrid. |
CurrentPageIndex | Gets or sets the index of the currently displayed page. |
EditItemIndex | Gets or sets the index of the item to be edited in the DataGrid. |
EditItemStyle | Gets the style properties of the item selected to be edited in the DataGrid. |
FooterStyle | Gets the style properties of the footer in the DataGrid. |
HeaderStyle | Gets the style properties of the header in the DataGrid. |
Items | Gets a collection of the DataGridItem objects in the DataGrid. This represents each individual item in the DataGrid. |
ItemStyle | Gets the style properties of the items in the DataGrid. |
PageCount | Gets the total number of pages that is required to display all the items in the DataGrid. |
PagerStyle | Gets the style property of the paging elements of the DataGrid. |
PageSize | Gets or sets how many items are to be displayed on each page of the DataGrid. |
SelectedIndex | Gets or sets the index of the item selected in the DataGrid. |
SelectedItem | Gets a DataGridItem object that contains the selected item in the DataGrid. |
SelectedItemStyle | Gets the style properties of the currently selected item in the DataGrid. |
ShowFooter | Gets or sets a Boolean value that determines whether the footer of the DataGrid is displayed. |
ShowHeader | Gets or sets a Boolean value that determines whether the header of the DataGrid is displayed. |
VirtualItemCount | Gets or sets the virtual number of items in the DataGrid control when custom paging is used. |
That's a lot of properties, isn't it? Well, that's not the end of it. Just like the DataList, the DataGrid provides a lot of powerful individual controls for the display and function of the data in the DataGrid. They differ, though. The DataList and Repeater are definitely focused on controlling the contents of each row of items. The DataGrid gives much more power by the addition of column templates that handle different types of function (see Table 9.11).
Template | Description |
---|---|
BoundColumn | Creates a column that is populated with data from a specific field in the data source. |
ButtonColumn | Creates a column that is populated with a command button for each item in the column. |
EditCommandColumn | Displays common edit commands such as Edit, Update, and Cancel. |
HyperlinkColumn | Creates a column of hyperlinks created from data from the data source. |
TemplateColumn | Creates a column that enables you to create templates within the column to control the HTML the column contains. |
The column templates all share a base set of properties, plus they have properties all their own, as well. Table 9.12 shows you the base properties first.
Property | Description |
---|---|
FooterStyle | Gets the style properties for the footer section of the column. |
FooterText | This is the text that is displayed in the bottom cell after all the items to be displayed. |
HeaderImageURL | The URL of the image that is rendered in the column heading. This overrides the HeaderText property. |
HeaderStyle | Gets the style properties for the header section of the column. |
HeaderText | This is the text that is displayed in the column heading. |
ItemStyle | Gets the style properties for the item cells of the column. |
SortExpression | The name of the field by which to sort the data source. |
Visible | A Boolean value that determines whether the column is displayed. |
As I said, each column template not only has the previous properties, but they also have unique properties that give them their individual function, as described in Tables 9.13 9.17.
Property | Description |
---|---|
DataField | Identifies the field in the data source that is the source for the column. |
DataFormatString | A formatting expression string that describes how to display the data in the column. |
ReadOnly | A Boolean value that determines whether the field can be edited if the row enters edit mode. |
Note |
The DataFormatString and the DataTextFormatString properties in later columns are powerful properties that allow you to set formatting for data that appears in a columns, such as formatting currency, dates, or numbers. This subject is pretty lengthy for discussion here but the .NET Framework SDK has an exhaustive amount of data on this subject, which you can start to investigate at the following URL: ms-help://MS.NETFrameworkSDK/cpguidenf/html/cpconformattingoverview.htm |
Property | Description |
---|---|
ButtonType | The type of button used when rendered. The valid options are LinkButton and PushButton. |
CommandName | Gets or sets the name of the command to perform if the button is clicked. |
DataTextField | The name of the field in the data source that will be bound to the button's text property. |
DataTextFormatString | Formatting expression string that describes how to display the data in the column. |
Text | Gets or sets the text property of the button in the column. If the DataTextField is set, this property is overridden. |
Property | Description |
---|---|
ButtonType | The type of button used when rendered. The valid options are LinkButton and PushButton. |
EditText | Gets or sets the text displayed as the Edit LinkButton or PushButton. |
UpdateText | Gets or sets the text displayed as the Update LinkButton or PushButton. |
CancelText | Gets or sets the text displayed as the Delete LinkButton or PushButton. |
Property | Description |
---|---|
DataNavigateURLField | Identifies the field in the data source that provides the URL of what page to go to. |
DataNavigateURLFormatString | A formatting expression string that describes how to display the URL portion of the HyperlinkColumn of the data in the column. |
DataTextField | The name of the field in the data source that will be bound to the column's text property. |
DataTextFormatString | A formatting expression string that describes how to display the text in the column. |
NavigateURL | Gets or sets the URL of the page to move to. |
Target | Gets or sets the target window that the URL in NavigateURL is loaded. |
Text | Gets or sets the text of the hyperlink. |
Template | Description |
---|---|
HeaderTemplate | If specified, rendered one time before anything in any of the other templates. |
ItemTemplate | Required; renders once for each item within the bound data source. |
EditItemTemplate | If specified, renders for the item selected for editing in the DataList control. |
FooterTemplate | If specified, renders once after all the items of the datasource have been rendered. |
With all these different elements, you can begin to see that the sky's the limit with regard to the control you can exercise when using the DataGrid control. We are going to go over a bunch of examples that cover much of the different functionality of the DataGrid. Of course, you could write a short (maybe even long) book to cover and build examples of what the DataGrid can do, but what I will cover here will give you solid examples of using the most common functions that the DataGrid provides. Look first at a simple example of just populating a DataGrid with information.
<%@ page language="vb" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SQLClient"%> <script runat=server> Sub Page_Load(sender As Object, e As EventArgs) if Not IsPostBack then DataSub end if end sub Sub DataSub() dim OurCommand as SQLCommand dim OurConnection as SQLConnection dim OurDataAdapter as SQLDataAdapter dim OurDataSet as New DataSet() OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password;database=Northwind") OurCommand = New SQLCommand("Select Top 10 ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products",OurConnection) OurDataAdapter = New SQLDataAdapter(OurCommand) OurDataAdapter.Fill(OurDataSet, "Products") dim OurDataTable as New DataView(OurDataSet.Tables("Products")) OurDataGrid.DataSource = OurDataTable OurDataGrid.DataBind() End Sub </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" runat="server" /> </body> </html>
<%@ page language="c#" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { DataSub(); } } void DataSub() { SqlCommand OurCommand; SqlConnection OurConnection; SqlDataAdapter OurDataAdapter; DataSet OurDataSet; OurDataSet = new DataSet(); OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password;database=Northwind"); OurCommand = new SqlCommand("Select Top 10 ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products",OurConnection); OurDataAdapter = new SqlDataAdapter(OurCommand); OurDataAdapter.Fill(OurDataSet, "Products"); DataView OurDataTable = new DataView(OurDataSet.Tables["Products"]); OurDataGrid.DataSource = OurDataTable; OurDataGrid.DataBind(); } </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" runat="server" /> </body> </html>
If you look at Figure 9.9, you can see that displaying the contents of products in DataGrid is quite simple. The data source pulls information out of the Northwind database and binds it to the DataGrid. In this simple example, the DataGrid, without intervention, creates the proper number of columns and populates the table cells with the data. Just set a few properties and we've got a hot-looking table of data delivered to the browser.
As I described earlier, the column templates give you a lot of power over formatting data within specific columns. Look at a few of the column types in action. Take notice that the AutoGenerateColumns property is set to false in the DataGrid's opening tag, because the columns will be created manually with column templates.
<%@ page language="vb" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SQLClient"%> <script runat=server> Sub Page_Load(sender As Object, e As EventArgs) if Not IsPostBack then DataSub end if If Request.Params("Product") <> "" Then OurLabel.Text = "You Chose: " & Request.Params("Product") end if end sub Sub DataSub() dim OurCommand as SQLCommand dim OurConnection as SQLConnection dim OurDataAdapter as SQLDataAdapter dim OurDataSet as New DataSet() OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password; database=Northwind") OurCommand = New SQLCommand("Select Top 10 ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products",OurConnection) OurDataAdapter = New SQLDataAdapter(OurCommand) OurDataAdapter.Fill(OurDataSet, "Products") dim OurDataTable as New DataView(OurDataSet.Tables("Products")) OurDataGrid.DataSource = OurDataTable OurDataGrid.DataBind() End Sub </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" runat="server"> <Columns> <asp:HyperLinkColumn HeaderText="Product Name" DataNavigateUrlFormatString="web_datagridcolumns_vb.aspx?Product={0}" DataNavigateUrlField="ProductName" DataTextField="ProductName" /> <asp:BoundColumn HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" /> <asp:BoundColumn HeaderText="Unit Price" DataField="UnitPrice" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Center" /> <asp:BoundColumn HeaderText="Stock" DataField="UnitsInStock" ItemStyle-HorizontalAlign="Center" /> </Columns> </asp:DataGrid> <asp:Label runat="server" /> </body> </html>
<%@ page language="c#" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { DataSub(); } if (Request.Params["Product"] != null) { OurLabel.Text = "You Chose: " + Request.Params["Product"]; } } void DataSub() { SqlCommand OurCommand; SqlConnection OurConnection; SqlDataAdapter OurDataAdapter; DataSet OurDataSet; OurDataSet = new DataSet(); OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password; database=Northwind"); OurCommand = new SqlCommand("Select Top 10 ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products",OurConnection); OurDataAdapter = new SqlDataAdapter(OurCommand); OurDataAdapter.Fill(OurDataSet, "Products"); DataView OurDataTable = new DataView(OurDataSet.Tables["Products"]); OurDataGrid.DataSource = OurDataTable; OurDataGrid.DataBind(); } </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" runat="server"> <Columns> <asp:HyperLinkColumn HeaderText="Product Name" DataNavigateUrlFormatString="web_datagridcolumns_cs.aspx?Product={0}" DataNavigateUrlField="ProductName" DataTextField="ProductName" /> <asp:BoundColumn HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" /> <asp:BoundColumn HeaderText="Unit Price" DataField="UnitPrice" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="Center" /> <asp:BoundColumn HeaderText="Stock" DataField="UnitsInStock" ItemStyle-HorizontalAlign="Center" /> </Columns> </asp:DataGrid> <asp:Label runat="server" /> </body> </html>
In Figure 9.10, you can see the result of using column templates such as the BoundColumn and HyperLinkColumn. Notice the different properties in the HyperLinkColumn that allow you to link to where you want, as well as add item-specific data to the URL. Also look at how I formatted the currency datatype in the 3rd column and centered the alignment of the contents of the 3rd and 4th columns with the ItemStyle-HorizontalAlign property.
I want to move on to some of the built-in functionality in the DataGrid control. Sorting the contents of tabular data is a very useful function, and the DataGrid control isn't shy about sorting by any means.
<%@ page language="vb" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SQLClient"%> <script runat=server> dim OurSortField as string Sub Page_Load(sender As Object, e As EventArgs) if Not IsPostBack then DataSub end if end sub Sub DataSub() dim OurCommand as SQLCommand dim OurConnection as SQLConnection dim OurDataAdapter as SQLDataAdapter dim OurDataSet as New DataSet() OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password; database=Northwind") OurCommand = New SQLCommand("Select Top 10 ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products",OurConnection) OurDataAdapter = New SQLDataAdapter(OurCommand) OurDataAdapter.Fill(OurDataSet, "Products") dim OurDataTable as New DataView(OurDataSet.Tables("Products")) if OurSortField <> "" Then OurDataTable.Sort = OurSortField end if OurDataGrid.DataSource = OurDataTable OurDataGrid.DataBind() End Sub Sub DataSort(sender As Object, e As DataGridSortCommandEventArgs) OurLabel.Text= "You sorted by " + e.SortExpression.ToString() OurSortField = e.SortExpression DataSub End Sub </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" AllowSorting="True" OnSortCommand="DataSort" runat="server" > <Columns> <asp:BoundColumn HeaderText="Product Name" DataField="ProductName" SortExpression="ProductName" /> <asp:BoundColumn HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" /> <asp:BoundColumn HeaderText="Unit Price" DataField="UnitPrice" DataFormatString="{0:c}" SortExpression="UnitPrice" /> <asp:BoundColumn HeaderText="Stock" DataField="UnitsInStock" SortExpression="UnitsInStock" /> </Columns> </asp:DataGrid> <asp:Label runat="server" /> </form> </body> </html>
<%@ page language="c#" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <script runat=server> String OurSortField; void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { DataSub(); } } void DataSub() { SqlCommand OurCommand; SqlConnection OurConnection; SqlDataAdapter OurDataAdapter; DataSet OurDataSet; OurDataSet = new DataSet(); OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password; database=Northwind"); OurCommand = new SqlCommand("Select Top 10 ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products",OurConnection); OurDataAdapter = new SqlDataAdapter(OurCommand); OurDataAdapter.Fill(OurDataSet, "Products"); DataView OurDataTable = new DataView(OurDataSet.Tables["Products"]); if (OurSortField != null ) { OurDataTable.Sort = OurSortField; } OurDataGrid.DataSource = OurDataTable; OurDataGrid.DataBind(); } void DataSort(Object sender, DataGridSortCommandEventArgs e) { OurLabel.Text= "You sorted by " + e.SortExpression.ToString(); OurSortField = e.SortExpression; DataSub(); } </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" AllowSorting="True" OnSortCommand="DataSort" runat="server" > <Columns> <asp:BoundColumn HeaderText="Product Name" DataField="ProductName" SortExpression="ProductName" /> <asp:BoundColumn HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" /> <asp:BoundColumn HeaderText="Unit Price" DataField="UnitPrice" DataFormatString="{0:c}" SortExpression="UnitPrice" /> <asp:BoundColumn HeaderText="Stock" DataField="UnitsInStock" SortExpression="UnitsInStock" /> </Columns> </asp:DataGrid> <asp:Label runat="server" /> </form> </body> </html>
As you can see in Figure 9.11, the DataGrid control makes sorting the bound data easy by allowing you to pass an expression, which is the column's name in the data source, to the SortCommand, which is a function that sets a sort property on the data source.
With the sort functions, you can sort the data on the page, but what if you have more data in your data source than you want to display on your page? You have to give the user the ability to page through this data. As a note, doing this in traditional ASP was not fun.
ASP.NET's DataGrid control now makes this a total piece of cake. Look first at one method that works well for smaller amounts of data.
<%@ page language="vb" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SQLClient"%> <script runat=server> Sub Page_Load(sender As Object, e As EventArgs) if Not IsPostBack then DataSub end if end sub Sub DataSub() dim OurCommand as SQLCommand dim OurConnection as SQLConnection dim OurDataAdapter as SQLDataAdapter dim OurDataSet as New DataSet() OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password; database=Northwind") OurCommand = New SQLCommand("Select ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products",OurConnection) OurDataAdapter = New SQLDataAdapter(OurCommand) OurDataAdapter.Fill(OurDataSet, "Products") dim OurDataTable as New DataView(OurDataSet.Tables("Products")) OurDataGrid.DataSource = OurDataTable OurDataGrid.DataBind() OurLabel.Text = "Page " & (OurDataGrid.CurrentPageIndex + 1) & " of " & (OurDataGrid. PageCount) End Sub Sub OurPager(sender As Object, e As DataGridPageChangedEventArgs) OurDataGrid.CurrentPageIndex = e.NewPageIndex DataSub() end sub </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanged="OurPager" PageSize="10" PagerStyle-NextPageText="Next" PagerStyle-PrevPageText="Prev" PagerStyle-HorizontalAlign="Right" runat="server"> <Columns> <asp:BoundColumn HeaderText="Product Name" DataField="ProductName" /> <asp:BoundColumn HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" /> <asp:BoundColumn HeaderText="Unit Price" DataField="UnitPrice" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="right" /> <asp:BoundColumn HeaderText="Stock" DataField="UnitsInStock" ItemStyle-HorizontalAlign="center" /> </Columns> </asp:DataGrid> <asp:Label runat="server" /> </form> </body> </html>
<%@ page language="c#" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { DataSub(); } } void DataSub() { SqlCommand OurCommand; SqlConnection OurConnection; SqlDataAdapter OurDataAdapter; DataSet OurDataSet; OurDataSet = new DataSet(); OurConnection = new SqlConnection("Server=server; uid=newriders;pwd=password; database=Northwind"); OurCommand = new SqlCommand("Select ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products",OurConnection); OurDataAdapter = new SqlDataAdapter(OurCommand); OurDataAdapter.Fill(OurDataSet, "Products"); DataView OurDataTable = new DataView(OurDataSet.Tables["Products"]); OurDataGrid.DataSource = OurDataTable; OurDataGrid.DataBind(); OurLabel.Text = "Page " + (OurDataGrid.CurrentPageIndex + 1).ToString() + " of " + ( OurDataGrid.PageCount).ToString(); } void OurPager(Object sender, DataGridPageChangedEventArgs e) { OurDataGrid.CurrentPageIndex = e.NewPageIndex; DataSub(); } </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanged="OurPager" PageSize="10" PagerStyle-NextPageText="Next" PagerStyle-PrevPageText="Prev" PagerStyle-HorizontalAlign="Right" runat="server"> <Columns> <asp:BoundColumn HeaderText="Product Name" DataField="ProductName" /> <asp:BoundColumn HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" /> <asp:BoundColumn HeaderText="Unit Price" DataField="UnitPrice" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="right" /> <asp:BoundColumn HeaderText="Stock" DataField="UnitsInStock" ItemStyle-HorizontalAlign="center" /> </Columns> </asp:DataGrid> <asp:Label runat="server" /> </form> </body> </html>
Notice in the code how the CurrentPageIndex and PageCount properties are used to create a display to inform users about what page they're on and what the total pages are. You can, see the results of this code example in Figure 9.12. Notice that the navigation for paging was generated by the DataGrid, and all I needed to do was set a few properties.
This type of paging is fine for smaller amounts of data, but when you're dealing with larger amounts of data, it might make more sense to deliver to the data source only the data that you need for the current page. Doing so would prevent large amounts of data from being stored in the web server's memory. ASP.NET makes provision for this type of paging, where you take bite-sized portions of the data you want so that the server's memory usage is preserved. This technique of paging with the ASP.NET DataGrid is called chunking.
<%@ page language="vb" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SQLClient"%> <script runat=server> Dim i as integer Sub Page_Load(sender As Object, e As EventArgs) if Not IsPostBack then DataSub i = 0 end if end sub Sub DataSub() dim OurCommand as SQLCommand dim OurCountCommand as SQLCommand dim OurConnection as SQLConnection dim OurDataAdapter as SQLDataAdapter dim OurDataSet as New DataSet() OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password; database=Northwind") OurCountCommand = New SQLCommand("Select Count(*) From Products",OurConnection) OurCountCommand.Connection.Open() OurDataGrid.VirtualItemCount = OurCountCommand.ExecuteScalar() OurCountCommand.Connection.Close() OurCommand = New SQLCommand("Select ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products Where ProductID Between " & i & " and " & i + OurDataGrid. PageSize,OurConnection) OurDataAdapter = New SQLDataAdapter(OurCommand) OurDataAdapter.Fill(OurDataSet, "Products") dim OurDataTable as New DataView(OurDataSet.Tables("Products")) OurDataGrid.DataSource = OurDataTable OurDataGrid.DataBind() OurLabel.Text = "Page " & (OurDataGrid.CurrentPageIndex + 1) & " of " & (OurDataGrid. PageCount) End Sub Sub OurPager(sender As Object, e As DataGridPageChangedEventArgs) i = e.NewPageIndex * OurDataGrid.PageSize OurDataGrid.CurrentPageIndex = e.NewPageIndex DataSub() end sub </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanged="OurPager" PageSize="10" PagerStyle-NextPageText="Next" PagerStyle-PrevPageText="Prev" PagerStyle-HorizontalAlign="Right" AllowCustomPaging="true" runat="server" > <Columns> <asp:BoundColumn HeaderText="Product Name" DataField="ProductName" /> <asp:BoundColumn HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" /> <asp:BoundColumn HeaderText="Unit Price" DataField="UnitPrice" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="right" /> <asp:BoundColumn HeaderText="Stock" DataField="UnitsInStock" ItemStyle-HorizontalAlign="center" /> </Columns> </asp:DataGrid> <asp:Label runat="server" /> </form> </body> </html>
<%@ page language="c#" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <script runat=server> int i; void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { DataSub(); i = 0; } } void DataSub() { SqlCommand OurCommand; SqlCommand OurCountCommand; SqlConnection OurConnection; SqlDataAdapter OurDataAdapter; DataSet OurDataSet = new DataSet(); OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password; database=Northwind"); OurCountCommand = new SqlCommand("Select Count(*) From Products",OurConnection); OurCountCommand.Connection.Open(); OurDataGrid.VirtualItemCount = (int)OurCountCommand.ExecuteScalar(); OurCountCommand.Connection.Close(); OurCommand = new SqlCommand("Select ProductName, QuantityPerUnit, UnitPrice, UnitsInStock From Products Where ProductID Between " + i.ToString() + " and " + i. ToString() + OurDataGrid.PageSize,OurConnection); OurDataAdapter = new SqlDataAdapter(OurCommand); OurDataAdapter.Fill(OurDataSet, "Products"); DataView OurDataTable = new DataView(OurDataSet.Tables["Products"]); OurDataGrid.DataSource = OurDataTable; OurDataGrid.DataBind(); OurLabel.Text = "Page " + (OurDataGrid.CurrentPageIndex + 1).ToString() + " of " + ( OurDataGrid.PageCount).ToString(); } void OurPager(Object sender, DataGridPageChangedEventArgs e) { i = e.NewPageIndex * OurDataGrid.PageSize; OurDataGrid.CurrentPageIndex = e.NewPageIndex; DataSub(); } </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3 style="font-family:Verdana">Our Products</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanged="OurPager" PageSize="10" PagerStyle-NextPageText="Next" PagerStyle-PrevPageText="Prev" PagerStyle-HorizontalAlign="Right" AllowCustomPaging="true" runat="server" > <Columns> <asp:BoundColumn HeaderText="Product Name" DataField="ProductName" /> <asp:BoundColumn HeaderText="Quantity Per Unit" DataField="QuantityPerUnit" /> <asp:BoundColumn HeaderText="Unit Price" DataField="UnitPrice" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="right" /> <asp:BoundColumn HeaderText="Stock" DataField="UnitsInStock" ItemStyle-HorizontalAlign="center" /> </Columns> </asp:DataGrid> <asp:Label runat="server" /> </form> </body> </html>
When you look at Figure 9.13, you can see that the results don't really look any different to the end user, but the web server is handling only 10 records at a time, rather than the 80 potential records that it would contain for all 8 pages of this data source. Notice the creation of a variable called i in the OurPager function. When this is passed to the data source, this value is used to deliver back only those records for the desired page.
Displaying, sorting, and navigating in the DataGrid is pretty cool, but it doesn't stop there. The DataGrid also provides ways for you to edit your data right within the DataGrid, as well. Take a look.
<%@ page language="vb" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <script runat=server> Sub Page_Load(sender As Object, e As EventArgs) if Not IsPostBack then DataSub end if end sub Sub DataSub() dim OurCommand as SqlCommand dim OurConnection as SqlConnection dim OurDataAdapter as SqlDataAdapter dim OurDataSet as New DataSet() OurConnection = New SqlConnection("Server=server;uid=newriders;pwd=password; database=Northwind") OurCommand = New SqlCommand("Select EmployeeID, FirstName, LastName From Employees", OurConnection) OurDataAdapter = New SqlDataAdapter(OurCommand) OurDataAdapter.Fill(OurDataSet, "Employees") dim OurDataTable as New DataView(OurDataSet.Tables("Employees")) OurDataGrid.DataSource = OurDataTable OurDataGrid.DataBind() End Sub Sub Edit(sender As Object, e As DataGridCommandEventArgs) OurDataGrid.EditItemIndex = e.Item.ItemIndex DataSub End Sub Sub Cancel(sender As Object, e As DataGridCommandEventArgs) OurDataGrid.EditItemIndex = -1 DataSub End Sub Sub Update(sender As Object, e As DataGridCommandEventArgs) dim objFirstName, ObjLastName as TextBox dim FirstName, LastName, EmployeeID as String objFirstName = e.Item.Cells(1).Controls(0) objLastName = e.Item.Cells(2).Controls(0) EmployeeID = e.Item.Cells(0).Text FirstName = objFirstName.Text LastName = objLastName.Text dim OurCommand as SqlCommand dim OurConnection as SqlConnection OurConnection = New SqlConnection("Server=server;uid=newriders;pwd=password; database=Northwind") OurCommand = New SqlCommand("Update Employees Set FirstName = '" & FirstName & "', LastName = '" & LastName & "' Where EmployeeID = " & EmployeeID, OurConnection) OurCommand.Connection.Open() OurCommand.ExecuteNonQuery() OurCommand.Connection.Close() OurDataGrid.EditItemIndex = -1 DataSub End Sub </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" OnEditCommand="Edit" OnCancelCommand="Cancel" OnUpdateCommand="Update" runat="server"> <Columns> <asp:BoundColumn HeaderText="EmployeeID" DataField="EmployeeID" readonly="true" /> <asp:BoundColumn HeaderText="First Name" DataField="FirstName" /> <asp:BoundColumn HeaderText="Last Name" DataField="LastName" /> <asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update"/> </Columns> </asp:DataGrid> </form> </body> </html>
<%@ page language="c#" runat="server"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient"%> <script runat=server> void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { DataSub(); } } void DataSub() { SqlCommand OurCommand; SqlConnection OurConnection; SqlDataAdapter OurDataAdapter; DataSet OurDataSet = new DataSet(); OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password; database=Northwind"); OurCommand = new SqlCommand("Select EmployeeID, FirstName, LastName From Employees", OurConnection); OurDataAdapter = new SqlDataAdapter(OurCommand); OurDataAdapter.Fill(OurDataSet, "Employees"); DataView OurDataTable = new DataView(OurDataSet.Tables["Employees"]); OurDataGrid.DataSource = OurDataTable; OurDataGrid.DataBind(); } void Edit(Object sender, DataGridCommandEventArgs e) { OurDataGrid.EditItemIndex = e.Item.ItemIndex; DataSub(); } void Cancel(Object sender, DataGridCommandEventArgs e) { OurDataGrid.EditItemIndex = -1; DataSub(); } void Update(Object sender, DataGridCommandEventArgs e) { TextBox objFirstName, objLastName; string FirstName, LastName; int EmployeeID; objFirstName = (TextBox)e.Item.Cells[1].Controls[0]; objLastName = (TextBox)e.Item.Cells[2].Controls[0]; EmployeeID = Int32.Parse(e.Item.Cells[0].Text); FirstName = objFirstName.Text; LastName = objLastName.Text; SqlCommand OurCommand; SqlConnection OurConnection; OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password; database=Northwind"); OurCommand = new SqlCommand("Update Employees Set FirstName = '" + FirstName + "', LastName = '" + LastName + "' Where EmployeeID = " + EmployeeID, OurConnection); OurCommand.Connection.Open(); OurCommand.ExecuteNonQuery(); OurCommand.Connection.Close(); OurDataGrid.EditItemIndex = -1; DataSub(); } </script> <html> <head> <title>Web Datagrid</title> </head> <body bgcolor="#FFFFFF" text="#000000"> <form runat="server"> <h3 style="font-family:Verdana">Employees</h3> <asp:DataGrid BorderWidth="1" BorderColor="#000000" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="12px" HeaderStyle-BackColor="#AAAAAA" ItemStyle-BackColor="#EEEEEE" AutoGenerateColumns="false" OnEditCommand="Edit" OnCancelCommand="Cancel" OnUpdateCommand="Update" runat="server"> <Columns> <asp:BoundColumn HeaderText="EmployeeID" DataField="EmployeeID" readonly="true" /> <asp:BoundColumn HeaderText="First Name" DataField="FirstName" /> <asp:BoundColumn HeaderText="Last Name" DataField="LastName" /> <asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update"/> </Columns> </asp:DataGrid> </form> </body> </html>
Notice in the preceding code example, in the DataGrid opening tag, three events called OnEditCommand, OnUpdateCommand, and OnCancelCommand. The events occur when you click on their corresponding links in the EditCommandTemplate column and call the functions to which their values are set. This is how the editing capability of the DataGrid is supplied.
You can see the results of this code example in Figure 9.14. Without ever creating a single input text box, the DataGrid produces the interface element necessary to perform edit capabilities. You must write what you want to happen within these functions, but all the interface work is done for you. Voilá!!!
Top |