Finishing the Sample Application


A lot of database programming involves running queries. Queries are statements written in SQL, the language of databases. They are phrases that almost read like plain English, and that tell the database how to select, edit, insert or delete records to a table. A common SQL statement is a statement that selects a number of records based on a criterion, normally called a Where clause.

Here is a typical SQL statement: "select * from contacts where LastName='Mojica' and FirstName='Jose'" . The word select does what it implies, brings back some information. The asterisk after the select tells the database that you want all fields from the table. If we only cared about the phone field we could have said: "select Phone from..." . After the fields we tell the database what table to run the query on, that is, the from contacts part. Then comes the Where clause. Without a Where clause the query would return every record in the table. With the Where clause the query returns only the records that match the criteria.

So why are we talking about queries and SQL? Because in this part of the sample application, you're going to use your knowledge of the Split and Format commands to build some good old SQL statements. We're going to display a form in which users can search for a person in the contact list. They will enter the person's first and last name in the search field. Your job will be to separate the first name from the last name, then build a query to search for that first name and last name . If they enter a blank in the search field, the program should display all the records in the table.

To finish the sample application:

  1. Choose Project > Add Web Form. You will see the dialog in Figure 4.58 . Enter contacts.aspx for the file name and press Enter.

    Figure 4.58. If you have been doing the sample applications in each chapter you are now quite familiar with this dialog. It enables you to add a new file to your project.

    graphics/04fig58.gif

  2. Create a form that looks like the form in Figure 4.59 . Do so by entering the HTML directly into the editor ( Figure 4.60 (on next page). You can also download the skeleton file for this project from the Peachpit Web site.

    Figure 4.59. The Contacts Web page has a table with contact information. The search field lets you enter a name (first name and last name), then when you click the Find button the grid shows the matching records.

    graphics/04fig59.gif

    Figure 4.60 You can recreate the Contacts Web page using the HTML here.
     <%@ Page language="c#"            Codebehind="contacts.aspx.cs"            AutoEventWireup="false"            Inherits="stringproject.contacts" %> <HTML>    <HEAD>       <title>contacts</title>    </HEAD>    <body MS_POSITIONING="GridLayout">    <form id="contacts"     method="post" runat="server">      <asp:  Label  id="lblTitle"         style="Z-INDEX: 101; LEFT: 20px;         POSITION: absolute; TOP: 21px"         runat="server"         Font-Size="X-Large">  Contact Manager  </asp:Label>      <asp:  DataGrid  id="grdContacts"         style="Z-INDEX: 104; LEFT: 26px;         POSITION: absolute; TOP: 117px"         runat="server" Width="327px"         Height="119px"></asp:DataGrid>      <asp:  Label  id="lblSearch"         style="Z-INDEX: 102; LEFT: 25px;         POSITION: absolute; TOP: 82px"         runat="server" Width="67px">  Search:  </asp:Label>      <asp:  TextBox  id="txtSearch"         style="Z-INDEX: 103; LEFT: 98px;         POSITION: absolute; TOP: 81px"         runat="server" Width="204px">         </asp:TextBox>      <asp:  Button  id="btnFind"         style="Z-INDEX: 105; LEFT: 318px;         POSITION: absolute; TOP: 82px"         runat="server" Text="Find">         </asp:Button>      </form>    </body> </HTML> 
  3. Double-click on a blank space in the form. This will cause VS.NET to open the code editor and add a Page_Load function.

  4. Scroll up to the top of the file, and under the last using statement add the following: using eInfoDesigns.dbProvider .MySqlClient ;

  5. Right before the Page_Load function after all the variable declarations add the following declaration:

    private string ConnectionString; This line declares a string variable to hold the connection string.

  6. Inside the Page_Load function, add the code in Figure 4.61 . This code checks to see if there is a connection string stored in the Session object. If there isn't, it redirects back to the login window. This is a common practice in programs where there is a login window, because it protects against the situation in which a user enters the URL for the second page with the idea of bypassing the login page. The second thing that this code does is run a function called Search passing the value of null. You'll add this function next.

    Figure 4.61 Upon loading the page we check to see if the connection string already exists. If it doesn't that means some sneaky user tried to bypass the login screen and go directly to the Contacts page. Therefore, we redirect back to the login screen. If everything is fine we display all records from the Contacts table.
     private void Page_Load(object sender,                      System.EventArgs e) {  ConnectionString =   (string)Session   ["ConnectionString"];   if (ConnectionString == null   ConnectionString == "")   Response.Redirect("login.aspx");   Search(null);  } 
  7. Above the Page_Load function, add a new function described in Figure 4.62 . This code is for the Search function. The Search function takes in a Where clause as a parameter. If the Where clause is null or empty, then the function creates an SQL statement that selects all records. If the Where clause contains text, then the function uses Split to divide the text into first name and last name. The Split function looks for a space or a dash for the delimiter . It then builds an SQL statement using the Format command.

    Figure 4.62 This is the master Search function. It ultimately opens a connection to the database, runs the query to search for a contact, then binds the grid to the result set, which makes the grid display all the records returned by the query.
     private void Search(string whereClause) {    string SQLCmd;    if (whereClause != null &&        whereClause != "")    {        string[] segments=        whereClause.Split(' ','-');        SQLCmd = string.Format(        "select * from contacts where" +        " LastName='{0}' and" +        " FirstName='{1}'",        segments[1],segments[0]);    }    else       SQLCmd = "select * from contacts";    MySqlConnection conn = new    MySqlConnection(ConnectionString);    conn.Open();    MySqlCommand cmd = new    MySqlCommand(SQLCmd,conn);    grdContacts.DataSource =    cmd.ExecuteReader();    grdContacts.DataBind(); } 
  8. In Solution Explorer, right-click on contacts.aspx , then select Show Designer from the popup menu.

  9. Double-click the Find button to bring up the code editor. The wizard will add the btnFind_Click function. Add the code in Figure 4.63 . This code will just invoke the Search function you've added, passing the text from the search field as the input parameter.

    Figure 4.63 With the Search function in place, all we need to do now is call the function when the user clicks the Find button passing the contents of the search textbox as input to the function.
     private void btnFind_Click(object sender,                           System.EventArgs e) {  Search(txtSearch.Text);  } 

graphics/tick.gif Tips

  • The sample code should now be fully functional and ready to be tested .

  • SQL Server uses the same scheme for fetching data. The only difference between the code above and code for SQL Server would be that you would drop the "My" from all the class names . Instead of MySqlConnection you would use SqlConnection ; in place of MySqlCommand you would use SqlCommand , etc. All the SQL Server classes are under the System.Data.SqlClient namespace.


Fetching Data from a Database

The last five lines of code in the Search function have to do with data access, and haven't been discussed yet. The first line of the bunch creates a new MySqlConnection object and passes the connection string as a parameter to the new. The line after that one calls the Open function. The Open function does the actual connection to the database. Following that line is a statement that creates a MySqlCommand object. This object runs the query in the database. The two parameters used in creating the command are the command's SQL statement and an instance of the connection object. To actually run the query you call ExecuteReader. ExecuteReader returns a result set and that result set can be handed to the grid control, which reads through the records and displays a table with the information. That's all there is to it! Of course, there are a lot more things you can do with a database but they are all beyond the scope of this book.



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net