1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning Visual Basic .NET Database Programming phần 7 pot

69 236 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

Chapter 10 26 ASP.NET Way back in the mists of recent history, there was a time when Microsoft wasn't particularly interested in the Internet. In fact, for a while it looked like they were going to have nothing to do with the thing. But then certain strategists realized the importance that the Internet was likely to have, and managed to turn the company on a dime to start churning out Web and Internet tools. One technology that sprung out of this was Active Server Pages or ASP. This was, in this author's humble opinion, one of the best products ever to come out of Microsoft. Strangely, because Microsoft strategy was in a state of flux, it was released without much fanfare yet became as popular as it is today simply because developers loved it. Essentially, ASP allows developers to write software that the user can access through a Web browser rather than a separate program installed on their computer. Thanks to the nature of the Web, it allows developers to write server-specific, Microsoft platform code on the server, but as the application is "operated" through HTML, it's available to users on virtually any platform. Although this was, and is, possible without Microsoft technology, ASP supported the cut down version of Visual Basic called VBScript and coupled with very powerful and easy to use database access objects such as ADO, this made it possible for developers familiar with Visual Basic to build extremely powerful applications very quickly. With the advent of .NET comes Active Server Pages .NET, or ASP.NET. This technology takes the best of ASP and enhances it to not only provide all of the power of .NET through the Framework classes, but also to incorporate the powerful control-centric paradigm for building applications that we've seen on the desktop. What this means is that if we want to put a button on a Web page for the user to click, we can use the Toolbox to draw a button just as we would with a Windows Form. For this reason, the technology used to construct user interfaces in ASP.NET is known as "Web Forms". In this chapter, we're going to take a look at ASP.NET and Web Forms. We'll show you how to build basic Web pages as we create a small application that lets customers and salespeople check stock levels and prices over the Web. We then move on to take a look at how we can build a more complex application that lets us change data. Chapter 11 2 An Introduction Visual Studio .NET has some great tools for developers of ASP.NET sites. However, to use these tools you'll need a Web server either on your local computer or on your network so you can run the pages. By default, the FrontPage Server Extensions 2000 are installed on your local machine along with the rest of the .NET Framework, providing that you have Internet Information Services installed before you install the Framework. This software allows a Web site editing tool (like FrontPage or Visual Studio .NET) to connect to the server in order to upload pages or, alternatively, download existing pages for editing. In this chapter and the next, I'll assume that your computer does have the FrontPage Server Extensions 2000 correctly installed and enabled on your computer of choice. In this chapter, we use the term localhost to refer to your own desktop computer. This is an Internet- specific term that means, basically, "the local computer". It is used to refer to the computer that is running the current application or web page itself. Let's create an ASP.NET project now. Try It Out – Creating the Project 1. Open Visual Studio .NET and create a new Visual Basic – ASP.NET Web Application project. 2. Set the name of the project to MyWebSite and make sure that the Location is set as http://localhost/ Notice the line under the Location box saying Project will be created at http://localhost/MyWebSite. This is important as we'll need to refer to this later, so keep it in mind. 3. Click the OK button to create your new project. ASP.NET 3 How It Works At this point, Visual Studio .NET would have created your new project. The Solution Explorer, as with any other type of application, shows the files that make up the project. At this stage you can safely ignore most of these files. Right now, we're only concerned with the Web Form files, with an .aspx extension. These are the Web equivalent of Windows Forms. Let's start off our first Web Form by adding a button that will do something when clicked. Try It Out – Adding a Button to a Page 1. Right-click WebForm1 in the Solution Explorer and select View Designer to open it in Design view. Note the buttons at the bottom of the editor that tell us whether we are in Design or HTML view, and provide a quick way to switch from one mode to the other. 2. Using the Web Forms tab of the Toolbox, drag a Button control onto the page. 3. Open the Properties window as you would normally, and change the Button control's Text property to Press Me. Change the ID property to btnPressMe. Notice that Web Form controls do not have a Name property, but instead have an ID property. This is because Dynamic HTML (DHTML), a technology heavily used by ASP.NET, assumes that control names are referenced through a property called ID. Chapter 11 4 4. Double-click on the Button control. This will create a mouse click event handler, as you might expect, that we shall use to prove to the user that something has happened by changing the button text. Place the following code inside the Click handler: Private Sub btnPressMe_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPressMe.Click ' Set the text btnPressMe.Text = "Oh, that tickles!" End Sub 5. Run the project. An instance of Internet Explorer will pop up and display our button. 6. Now, press the button. You'll see this: How It Works You can see that the .NET approach to building forms for the Web is very similar to the approach when building forms for the desktop. We create a page, we add controls and we wire up events. When the project is run, Internet Explorer is run, given the URL of the Web application, namely http://localhost/MyWebSite/WebForm1.aspx. ASP.NET 5 You can see that this URL is built up from the details that we specified for our project earlier to create the full location of the project, including the server name (localhost), and of course the name of the form that we're using. Suppliers and Products As this book is all about working with databases, we'll delve into how we can present information taken from a database on an ASP.NET page. In this section, we'll produce a page that displays a list of suppliers. The user can select a supplier from the list to see all the products that that supplier deals with. ASP.NET makes heavy use of data binding, but the way it works in ASP.NET can be a little tricky to understand. Take care to follow the instructions given carefully. Try It Out – Showing a List of Suppliers 1. Using Solution Explorer, right-click on Global.asax and select View Code. At the top of the class definition, add the following: Public Class Global Inherits System.Web.HttpApplication ' Constants Public Const DbString As String = _ "integrated security=sspi;initial catalog=NorthwindSQL;data source=chimaera" Remember to change this database connection string to whatever works for your SQL set up. 2. Go back to the Solution Explorer, right click on the MyWebSite project and select Add | Add Web Form. Call it Suppliers. 3. When the Designer appears, make sure you're in Design view, and add a new DataList control from the Toolbox to the form. 4. Change the ID property of the new control to lstSuppliers. As I mentioned before, data binding in Web Forms is a fairly odd process. The DataList control isn't capable of presenting the data by itself, so we need to place the control into a special mode that lets us add other controls to present the data. Right-click on the DataList control and select Edit Template | Item Templates. The control is now in a mode where we can add controls to present each item. Chapter 11 6 5. Drag a HyperLink control from the Toolbox onto the box in the DataList labelled ItemTemplate: From this point on, to select the HyperLink control, use the drop-down at the top of the Properties window rather than trying to click on the control in the Designer. This will make your life far less frustrating! Of the four areas in the editor, we're only interested in ItemTemplate. We can use AlternatingItemTemplate to display "every other item", which is useful on occasions where we want each line in the list to have an alternate background color. Although we're not going to use the selection or editing features here, SelectedItemTemplate is used when the item is selected and EditItemTemplate is used when the item is being edited. 6. Select the HyperLink control now. Change its ID property to lnkSupplier. We now want to bind the row that we're working with to the Text property of the HyperLink control. Find the DataBindings property, which appears at the top of the Properties window in brackets. Click the ellipsis ("…") button to its right to make the window shown below appear. Select Text from the left-hand list, check Custom binding expression, and enter the code shown: ASP.NET 7 7. Click OK when you're happy you've entered the correct code. The displayed text of our HyperLinks is now bound to the CompanyName column of our data source. Later, we will be setting up URL links for these controls also, but for starters we'll just bind the Text property. 8. Next, we need to actually connect to the database and extract the list of suppliers. Double- click on the background of the form. This will open the Load event handler. Add this code: Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Connect to the database Dim connection As New SqlConnection(Global.DbString) connection.Open() ' Retreive the suppliers Dim command As New SqlCommand("SELECT * FROM SUPPLIERS", connection) Dim reader As SqlDataReader = command.ExecuteReader() ' Bind the DataList to the SqlDataReader lstSuppliers.DataSource = reader lstSuppliers.DataBind() ' Close the SqlDataReader and release the SqlCommand object reader.Close() command.Dispose() ' Close the database connection connection.Close() End Sub 9. Before we are ready to run the project, we need to add the following line to the beginning of Suppliers.aspx.vb, right at the top immediately preceding the Page_Load event: Imports System.Data.SqlClient 10.Right click on Suppliers.aspx in the Solution Explorer, and choose Set As Start Page. We're now ready to roll - choose Debug | Start, or press F5. You should see a list of suppliers displayed in your browser: Chapter 11 8 How It Works First, we'll look at how we retrieved the supplier list. Then we'll take a look at how that list was displayed. All ASP.NET projects can take advantage of Global.asax. This is a page that references a class called Global by default, and derives from c. This namespace defines events that we can catch and respond to, for example when the application is started (the first time that a page is requested after the server is rebooted) or whenever a user requests a page from the site. In our application, we've placed our connection string in the Global.asax page, and we can use that string constant from anywhere within our project to specify where our database can be found. Public Class Global Inherits System.Web.HttpApplication ' Constants Public Const DbString As String = _ "integrated security=sspi;initial catalog=NorthwindSQL;data source=chimaera" When Suppliers.aspx is loaded, the Page_Load event is fired. Suppliers.aspx.vb defines a class called Suppliers that is associated with the .aspx page by the process known as "code behind". By default, Visual Studio creates all new Web Form pages in this way, deriving the associated classes from System.Web.UI.Page. Event-handling code that we write is placed in this class, and we can also add our own methods and properties. In our case, we use the code behind to extract data from a database. Notice how we're using the DbString constant defined in Global.aspx. ' Connect to the database Dim connection As New SqlConnection(Global.DbString) connection.Open() Don't forget that almost everything happens on the server. When the page is requested, the Suppliers.aspx and Suppliers.aspx.vb files are both complied and executed on the server with the ultimate goal of generating HTML that can be sent down to the client. There are two important things to note here. Firstly, with ASP.NET, data binding is always read-only, which means that we can use a DataReader instead of a DataSet. ' Retreive the suppliers Dim command As New SqlCommand("select * from suppliers", connection) Dim reader As SqlDataReader = command.ExecuteReader() As described in Chapter 6, this provides fast, read-only, forward-only movement through the underlying data. This type of database access is sometimes called a "fire hose" cursor, because you can quickly reel more out, but it's not really possible to go backwards. The DataReader consumes less memory and performs faster than a DataSet at the cost of the advanced movement and manipulation features supported by the DataSet. When creating ASP.NET applications, you will probably find that in the vast majority of cases you won't need these features anyway. ASP.NET 9 The other important thing to notice is that Web Form controls do not automatically data bind when the DataSource property is set, unlike Windows Forms. You must explicitly call the DataBind method when you want the control to bind. ' Bind the DataList to the SqlDataReader lstSuppliers.DataSource = reader lstSuppliers.DataBind() Looking back at the DataList control, what happens is that for every data item in the source specified in the binding, new instances of any controls placed in the ItemTemplate area are created. In our case, these controls are HyperLink controls, the DataBindings property of which determines how data should be extracted from the current item to be bound and displayed on the control. It's the DataBinder.Eval call that we set up in the lnkSupplier DataBindings dialog that performs the actual magic to associate the text of each HyperLink with the name of each supplier as it is pulled out of the database. The Eval method ("eval" being short for "evalulate") is a general purpose method used in data binding for extracting data from other objects. It's a shared method of the System.Web.UI.DataBinder object. Let's have a closer look at that call now: DataBinder.Eval (Container.DataItem, "CompanyName") The first argument binds the HyperLink's Text property to the DataItem property of the HyperLink's container, which in this case is automatically set by ASP.NET to be our DataList. The second argument gives the name of a column, CompanyName, in the table that the control knows we're binding to. Now we shall move on to enhance this code so that the user can click on a supplier to show the products they supply. Try It Out – Binding URLs for the HyperLink Controls 1. Open Suppliers.aspx in Design view again. The DataList may be showing the text Databound several times, in which case you will need to right-click on it, and select Edit Template | Item Templates to make the lnkSupplier HyperLink control visible. 2. Select lnkSupplier from the drop down list at the top of the Properties window. Open the lnkSupplier DataBindings dialog again by clicking on the ellipsis button of the DataBindings property. Click on NavigateUrl in the Bindable Properties pane, check Custom binding expression and add the expression shown: [...]... horrendously complex.) If you are worried about performance, you might want to look into caching – see Beginning ASP.NET using VB.NET by Wrox (ISBN 1861005040) – or developing your own paging code that gets just the data you need Updating With Web Forms So far, we've used Web Forms to create a read-only view of a database Web Forms are equally capable at creating new data and making changes to existing data... Click Event Handler in ASP.NET 1 Double-click on the Go! Button in the Designer, and add the code below for the Button's Click handler Don't forget that we use the constant we defined on the Global class to get the database string for the connection Private Sub btnSearch_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSearch.Click ' Connect to the database Dim connection... section, we'll put together an application to edit customer details over the Web 28 ASP.NET Looking up Customers In the first part of this exercise, we'll build a basic page to edit the name of a company given a customer ID We're not going to use data binding in this example for the sake of simplicity A crucial point in ASP.NET is that we're working in a disconnected environment unlike with Windows Forms... to the right of the DataList and press Return Drag a DataGrid from the Toolbox and place it underneath the DataList Set its ID property to grdProducts ASP.NET 6 With the DataGrid selected, click on the Auto Format link in the Properties window 7 When you click Auto Format, a dialog should appear offering a selection of predefined formats that you can apply to the DataGrid Choose a format that you... the Data Field to unitprice Insert {0:c} in the Data formatting expression box This isn't just an extravagant twoway smiley: it also tells ASP.NET that this column is a currency, as explained later Click OK and run the project You should see the following: ASP.NET How It Works The neat part here is the format string The formatting codes it contains are universal throughout the Framework for converting... Connect to the database Dim connection As New SqlConnection(Global.DbString) connection.Open() ' Retreive the items Dim sql As String = _ "SELECT productname, unitprice, unitsinstock FROM products " & _ "WHERE productname LIKE '%" & Me.txtSearchFor.Text & "%'" Dim command As New SqlCommand(sql, connection) Dim dataset As New DataSet() Dim adapter As New SqlDataAdapter(command) 26 ASP.NET adapter.Fill(dataset)... SqlDataReader and release the SqlCommand object productsReader.Close() productsCommand.Dispose() End If ' Close the database connection connection.Close() End Sub 9 12 Now run the project When you click on a supplier, the products that supplier deals with should show up in the DataGrid ASP.NET How It Works When the browser makes a request to the server, it must supply all necessary information for the... precise control over the position of your controls, but your pages are more robust, and more compliant with older IE browsers and browsers from other vendors 14 ASP.NET An Inventory Web Application Now let's move on to create a practical ASP.NET business application that allows a salesperson, or customer, to search for products with a given name We'll present a list of those products together with the... together HTML forms in the past will recognize this technique – it's conceptually similar to storing information in HIDDEN elements on a page So let's create our basic form for changing the company name for a particular customer Try It Out – Editing a Database Field 1 Right-click on MyWebSite in Solution Explorer, and choose Add | Add Web Form Call the new form EditCustomer, and add two Buttons, four Labels... the very top of EditCustomer.aspx.vb: Imports System.Data.SqlClient 7 32 In Solution Explorer, right-click EditCustomer.aspx and select Set As Start Page, and run the project Leaving the default of FRANR in the customer ID TextBox, click the Look Up Customer button The customer ID isn't case-sensitive, but it must be an exact match ASP.NET 8 Change FRANR to SMURF, or some other customer ID that doesn't . page itself. Let's create an ASP .NET project now. Try It Out – Creating the Project 1. Open Visual Studio .NET and create a new Visual Basic – ASP .NET Web Application project. 2. Set the. version of Visual Basic called VBScript and coupled with very powerful and easy to use database access objects such as ADO, this made it possible for developers familiar with Visual Basic to build. Introduction Visual Studio .NET has some great tools for developers of ASP .NET sites. However, to use these tools you'll need a Web server either on your local computer or on your network so

Ngày đăng: 13/08/2014, 12:21