ASP.NET ExampleAs was mentioned in Chapter 10, having FreeDB in a relational format allows for as many queries as you can dream up. Just for a fun example, the ASP.NET page shown in Listing 11.4, allows you to enter a CD Title into a TextBox. Once the button is pushed, all of the track names are returned into a DataGrid on the page. Listing 11.4 shows the ASP.NET page, and Listing 11.5 shows the code behind C# file. Listing 11.4. ASP.NET Page<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
This HTML is created automatically by the IDE designer. By double-clicking the button, the IDE creates the event handler and attaches it to the button on the ASP.NET page in Listing 11.2 and a private variable for the Web service, the button click handler code is very simplistic. Listing 11.5. Corresponding C# Code Behind Fileusing System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace FreeDBWP { /// <summary> /// Summary description for WebForm1. /// </summary> public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.Button Button1; protected System.Web.UI.WebControls.DataGrid DataGrid1;private webservice.Service1 ws; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Button1.Click += new System.EventHandler(this.Button1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Button1_Click(object sender, System.EventArgs e) { try { if(this.TextBox1.Text.Length>0) { ws = new webservice.Service1(); this.DataGrid1.DataSource = ws.GetTracksForCd(this.TextBox1.Text); this.DataGrid1.DataBind(); } } catch(Exception ex) { Debug.WriteLine(ex.ToString()); } } } Figure 11-4. This also ties back to the beginning of the chapter as a great illustration of a server-side button click event handler populating a Datagrid for display to the user. Note the two X terminal windows running postmaster/postgresql and XSP. While this is not the most useful query, it does serve as a good proof of concept for operating system-independent ASP.NET and Web service development. |