Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 79 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
79
Dung lượng
873,33 KB
Nội dung
442 Chapter 9 • Using ADO.NET This line binds the TypedDataSet to the DataGrid: DataGrid1.DataSource = tdsOrders1 6. Set the Anchor property of the DataGrid to ALL and build the solu- tion.The finished form should look like Figures 9.7 and 9.8.After you press F5, click the button, and expand the default node. www.syngress.com Figure 9.7 Finished Form Figure 9.8 Orders Table 153_VBnet_09 8/15/01 2:31 PM Page 442 Using ADO.NET • Chapter 9 443 Click the plus sign to get a list of tables in our DataSet. Select the Orders table from the drop-down to get the view shown in Figure 9.8. In our example, we start out with a list of orders, and we can expand them by clicking the plus sign at the record selector in the far left of the grid.This pro- vides us with a list of relations. In our example, we only have the one, so select it, and the grid will change to show the detail records for that order.When you consider that we started with a project that consisted of dragging and dropping some objects from the Server Explorer and the toolbox, entering half a dozen lines of code, this is pretty powerful stuff! The WebForm DataGrid object in ASP.NET is quite a bit different as far get- ting one to operate.A few lines of code are all it takes to put one of these to work with some basic functionality.The following example creates a basic HTML table of our data with just a few lines of code.This is the line of code that will actually place the control on the form for us. Place it where you would like the grid to show up on the page (see CD file Chapter 09/Chapter9 Beta2/Samples/ wwwroot/Chapter9/DataGridSample.aspx): <asp:DataGrid id="DGOrders" runat="server"/> All that is left to do is to populate the grid with a data source: Private sConn As String = "<MyConnectionstring>" Private dsShippers As DataSet Private Sub BindData() Dim strSQLQuery As String Dim objConn As SqlClient.SqlConnection Dim objAdapter As SqlClient.SqlDataAdapter strSQLQuery = "SELECT * FROM Shippers" Create a connection to the SQL Server: objConn = New SqlClient.SqlConnection(sConn) Create a SqlDataAdapter using the connection and the SQL statement as parameters for the constructor: objAdapter = New SqlClient.SqlDataAdapter(strSQLQuery, objConn) www.syngress.com 153_VBnet_09 8/15/01 2:31 PM Page 443 444 Chapter 9 • Using ADO.NET Create the DataSet and fill it with the SqlDataAdapter object we created earlier: dsShippers = New DataSet() objAdapter.Fill(dsShippers, "Shippers") Set the DataSource of our data grid to the newly created DataSet, and call the DataBind method to finish the grid: DGShippers.DataSource = dsShippers.Tables("Shippers").DefaultView DGShippers.DataBind() End Sub Call the BindData procedure from the Page_Load event.The finished product is shown in Figure 9.9. The WebForm DataGrid can be further enhanced with the Columns collec- tion that may contain any or all of the objects in Table 9.5.These give us the power to create some very appealing functionality with only a few lines of code. www.syngress.com Figure 9.9 DataGrid Sample 153_VBnet_09 8/15/01 2:31 PM Page 444 Using ADO.NET • Chapter 9 445 Table 9.5 Column Collection Objects Column Name Description BoundColumn Default column, it is bound to data and allows us to control the ordering and rendering of the column. HyperLinkColumn Presents the bound data in HyperLink controls. The text and URL of the hyperlink can be static or bound to data. ButtonColumn Represents a column with a set of push button controls. Bubbles a user command from within a row to an Event Handler on the grid. Not bound to data. The developer must write a handler to perform the action specified. TemplateColumn Defines a template used to format controls within a column. EditCommandColumn Displays Edit, Update, and Cancel links to allow the user to edit line items. The DataGrid will present the user with appropriate links and text boxes for the line being edited, while displaying the other rows in read-only text. The EditCommandColumn creates the DataGrid with some options for the HTML output. It is also important to note that the OnEditCommand, OnCancelCommand, and OnUpdateCommand are mapped to server-side sub- procedures that we have to write.Also, turn off the AutoGenerateColumns, which defaults to true: <asp:DataGrid id="DGOrders" runat="server" BorderColor="black" BorderWidth="1" CellPadding="3" Font-Size="8pt" HeaderStyle-BackColor="#aaaadd" OnEditCommand="DGShippers_Edit" OnCancelCommand="DGShippers_Cancel" OnUpdateCommand="DGShippers_Update" AutoGenerateColumns="false" > www.syngress.com 153_VBnet_09 8/15/01 2:31 PM Page 445 446 Chapter 9 • Using ADO.NET Here we define our columns.The first column is the EditCommandColumn. The options are self-explanatory.The EditText, CancelText, and UpdateText are the text that will show up in our hyperlinks to perform the desired action.The other columns are standard BoundColumns that display the data from the Shippers table: <Columns> <asp:EditCommandColumn EditText="Edit" CancelText="Cancel" UpdateText="Update" ItemStyle-Wrap="false" HeaderText="Edit Command Column" HeaderStyle-Wrap="false" /> <asp:BoundColumn HeaderText="Shipper ID" ReadOnly="true" _ DataField="ShipperID"/> <asp:BoundColumn HeaderText="Company Name" _ DataField="CompanyName"/> <asp:BoundColumn HeaderText="Phone" DataField="Phone"/> </Columns> </asp:DataGrid> It is important to note that while both of these controls are called DataGrid, they inherit from different base classes. Microsoft has named many of the methods and properties for these controls the same, but do not take this for granted.The name may be the same, but the implementation is quite different. DataList A DataList is very similar to the WebForm DataGrid, with a few exceptions. It uses template tags, is a WebForm control, and inherits from the WebForm namespace. After adding a new WebForm to a Web project, place the following code between the opening and closing form tags.This block of code defines our DataList and binds the DataList_Click procedure to the OnItemComand event for the list (see CD file Chapter 09/Chapter9 Beta2/Samples/wwwroot/Chapter9/ DataListSmaple.aspx): www.syngress.com 153_VBnet_09 8/15/01 2:31 PM Page 446 Using ADO.NET • Chapter 9 447 <asp:DataList id="DLShippers" runat="server" Width="100%" OnItemCommand="DataList_Click" RepeatColumns="1" > This block of code defines the default formatting of each row in our list: <ItemTemplate> <asp:Table Runat="server" Width="100%" ID=Table1> <asp:TableRow> <asp:TableCell> <asp:LinkButton id="Select" _ runat="server" Text="Select " CommandName="Select"/> <asp:Label id="lblShipper" _ runat="server"> <% #DataBinder.Eval(Container.DataItem, "CompanyName") %> </asp:Label> </asp:TableCell> </asp:TableRow> </asp:Table> </ItemTemplate> This block of code defines the formatting of the row we selected in the browser: <SelectedItemTemplate> <asp:Table Runat="server" Width="100%" ID=Table2> <asp:TableRow BackColor="#EEEEEE"> <asp:TableCell> <asp:Label id="lblPhone"_ runat="server"> <% #DataBinder.Eval(Container.DataItem, "Phone") %> </asp:Label> www.syngress.com 153_VBnet_09 8/15/01 2:31 PM Page 447 448 Chapter 9 • Using ADO.NET </asp:TableCell> </asp:TableRow> </asp:Table> </SelectedItemTemplate > </asp:DataList> The following code goes into the CodeBehind file created for your WebForm: Private sConn As String = "<MyConnectionString>" Private dsShippers As DataSet Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here If Not Page.IsPostBack Then BindData() End If End Sub Private Sub BindData() Dim strSQLQuery As String Dim objConn As SqlClient.SqlConnection Dim objAdapter As SqlClient.SqlDataAdapter strSQLQuery = "SELECT * FROM Shippers" objConn = New SqlClient.SqlConnection(sConn) objAdapter = New SqlClient.SqlDataAdapter(strSQLQuery, objConn) dsShippers = New DataSet() objAdapter.Fill(dsShippers, "Shippers") www.syngress.com 153_VBnet_09 8/15/01 2:31 PM Page 448 Using ADO.NET • Chapter 9 449 DLShippers.DataSource = sShippers.Tables("Shippers").DefaultView DLShippers.DataBind() End Sub This procedure handles the event bubbled up from the browser: Public Sub DataList_Click(ByVal Source As Object, _ ByVal E As DataListCommandEventArgs) DLShippers.SelectedIndex = E.Item.ItemIndex Call BindData() End Sub Figure 9.10 shows the result. This page shows the usage of the template tags and some of the options avail- able.Template tags give us some options for formatting the different rows.They really make the data controls very flexible and remove many of the reasons we have for not using them.The available templates vary depending on which DataControl you are using,Table 9.6 lists the available templates for the DataList control. www.syngress.com Figure 9.10 DataList Output 153_VBnet_09 8/15/01 2:31 PM Page 449 450 Chapter 9 • Using ADO.NET Table 9.6 DataList Template Items Template Name Description ItemTemplate Required template that provides the style for items in the DataList. AlternatingItemTemplate Provides the style for alternating items in the DataList. SeparatorTemplate Provides the style for the separator between items in the DataList. SelectedItemTemplate Provides the style for the currently selected item in the DataList. EditItemTemplate Provides the style for the item currently being edited in the DataList. HeaderTemplate Provides the style for the header of the DataList. FooterTemplate Provides the style for the footer of the DataList. Repeater The Repeater object is a Web form control that allows us to create templates out of HTML, and then bind them to data—sort of like making our own grid con- trol, except that we can use data binding.The tricky part of setting up the repeater is the use of template tags.An example is worth a thousand words, so here is a repeater bound to a DataSet that contains the Shippers table from the Northwind database (see CD file Chapter 09/Chapter9 Beta2/Samples/ wwwroot/Chapter9/RepeaterSample.aspx): <html> <head> <title>Using ADO.NET Repeater Sample</title> </head> <body> <h3><font face=Verdana>Repeater Example</FONT></H3> <form id=Form1 runat="server"> <b>Shippers:</b> <p><asp:repeater id=RPTRShippers runat="server"> <HeaderTemplate> <table border=1> www.syngress.com 153_VBnet_09 8/15/01 2:31 PM Page 450 Using ADO.NET • Chapter 9 451 <tr> <th>Company Name</th> <th>Phone</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <%# DataBinder.Eval(Container.DataItem, "CompanyName") %> </td> <td> <%# DataBinder.Eval(Container.DataItem, "Phone") %> </td> </tr> </template> <AlternatingItemTemplate> <tr bgcolor="#cccccc"> <td > <%# DataBinder.Eval(Container.DataItem, "CompanyName") %> </td> <td > <%# DataBinder.Eval(Container.DataItem, "Phone") %> </td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </FORM> </P> </body> </html> www.syngress.com 153_VBnet_09 8/15/01 2:31 PM Page 451 [...]... server: … www.syngress.com 477 ... form by setting the following properties: Text: Customer ID ID: lblCustomerID 6 Place a text box control next to the second label control and set its properties to: Text: “” (empty) ID: txtCustomerID 7 Press Enter and then place a button control and change its properties to: Text: Get Order Details ID: cmdGetDetails After placing the controls, your Web form should resemble Figure 10.3 8 Save the Form... data source to free up resources and respond to the next user Using the SQL Server Data Provider The SQL Server data provider is written explicitly to provide data access to Microsoft SQL Server version 7 and later.This set of classes takes advantage of the SQL Server API in a way that makes it more efficient for data access than going through the OLE DB libraries The SQL Server data provider’s core objects... AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="Chapter10.WebForm1"%> Customer Order Details . across networks or the Internet and takes care of many of the complexities of communi- cating across networks. ; XML is key to remoting in ADO .NET. Data Controls ; The data controls in VB. NET are. Sample 153_VBnet_09 8/15/01 2:31 PM Page 453 454 Chapter 9 • Using ADO .NET Summary In this chapter, we discussed the base functionality in ADO .NET. We discussed XML, and how it relates to ADO .NET. By. "Phone") %> </asp:Label> www.syngress.com 153_VBnet_09 8/15/01 2:31 PM Page 4 47 448 Chapter 9 • Using ADO .NET </asp:TableCell> </asp:TableRow> </asp:Table> </SelectedItemTemplate