The DataGrid Demo

This demo binds the employees table to a DataGrid, allows users to click a Send button, and then e-mails a notification about the employee to the e-mail address in a TextBox. You can see the demo below as it first appears.

The User Interface

At the heart of the user interface is a DataGrid named Employees. Below the DataGrid is a Label named ErrorMessage that's used to alert users to any exception messages that have been caught. And below that is a TextBox named Email into which users type an email address.

The DataGrid has three columns when it renders: one for the employee's name, one for the employee's hire date, and one for a Send button. Within the DataGrid is a server control: a Label named Name that contains the employees's name. The DataGrid code from the .aspx file is below. A discussion of the code follows the code.

 <asp:datagrid  runat="server" AutoGenerateColumns="False">   <Columns>     <asp:TemplateColumn runat="server" HeaderText="Name">       <ItemTemplate>         <asp:Label  Runat="server"            Text='<%# DataBinder.Eval(Container.DataItem, "lname") +             ", " + DataBinder.Eval(Container.DataItem, "fname") %>' />       </ItemTemplate>     </asp:TemplateColumn>     <asp:BoundColumn DataField="hire_date"        DataFormatString="{0:MM/dd/yyyy}" HeaderText="Hire Date" />     <asp:ButtonColumn CommandName="select" HeaderText="Send Email"        DataTextField="lname" DataTextFormatString="Send" />   </Columns> </asp:datagrid> 

Unlike Repeaters and DataLists, Column tags are used instead of ItemTemplate and AlternatingItemTemplate tags. Within the Column tag are three other tags: an asp:TemplateColumn, an asp:BoundColumn, and an asp:ButtonColumn tag. These three tags function in different ways, as you'll see.

The asp:TemplateColumn tag lets you use an ItemTemplate tag, as with Repeaters and DataLists. The ItemTemplate tag has a Label object inside of it, just as the Repeater and DataList demos did. The Label is named Name, and it is populated with the last and first name of the employee.

The asp:BoundColumn provides an easy way to describe a column that'll appear in the DataGrid. Its attributes let you set the data field, the header text, and how to format the data. Being able to format the data using the string formatting options is a big help when you need to carefully manage the formatting.

The asp:ButtonColumn lets you add a button that users can use to make a selection that can fire an event. This particular button fires the Employees_SelectedIndexChanged() method (seen later).

The Code behind the DataGrid Demo

There are two methods behind the DataGrid demo that we'll take a look at. The first is the Page_Load() Method, and the second is the Employees_SelectedIndexChanged() method. Both methods are described in the next two sections.

NOTE: In addition to the System.Data.SqlClient namespace, this demo also requires the System.Web.Mail namespace because of the use of the mail objects. Toward the top of each source code module, you'll see the following:

C#
 using System.Web.Mail; 
VB
 Imports System.Web.Mail 


The Page_Load() Method of the DataGrid Demo

The code for the Page_Load() method follows. A discussion of the code is immediately below it.

C#
 private void Page_Load(object sender, System.EventArgs e) {   // Only populate the DataGrid if this is not a post back.   if( !IsPostBack )   {     // Create a connection object.     SqlConnection objConnection =      new SqlConnection("server=localhost;database=pubs;uid=sa;pwd=");     // Use a try/catch/finally construct to     //   gracefully handle errors.     try     {       // Open the connection.       objConnection.Open();       // Create the command object. We'll select all       //   author first and last name along with phone.       SqlCommand objCommand =         new SqlCommand( "SELECT lname,fname,hire_date FROM employee " +         "ORDER BY lname,fname",         objConnection );       // Populate a reader.       SqlDataReader objReader = objCommand.ExecuteReader();       // Set the DataGrid's data source and then       //   call the DataBind() method.       Employees.DataSource = objReader;       Employees.DataBind();       // Close the reader.       objReader.Close();     }     catch( Exception ex )     {       // Display the error message to the reader.       ErrorMessage.Text = ex.Message.ToString();     }     finally     {       // See if the connection is open.       if( objConnection.State == ConnectionState.Open )       {         // Close it if it is open.         objConnection.Close();       }     }   } } 
VB
 Private Sub Page_Load(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles MyBase.Load     ' Only populate the DataGrid if this is not a post back.     If Not IsPostBack Then      ' Create a connection object.      Dim objConnection As _       New SqlConnection("server=localhost;database=pubs;uid=sa;pwd=")         ' Use a try/catch/finally construct to         '   gracefully handle errors.         Try             ' Open the connection.             objConnection.Open()            ' Create the command object. We'll select all            '   author first and last name along with phone.            Dim objCommand As _             New SqlCommand( _               "SELECT lname,fname,hire_date FROM employee " + _              "ORDER BY lname,fname", _              objConnection)             ' Populate a reader.             Dim objReader As SqlDataReader = objCommand.ExecuteReader()             ' Set the DataGrid's data source and then             '   call the DataBind() method.             Employees.DataSource = objReader             Employees.DataBind()             ' Close the reader.             objReader.Close()         Catch ex As Exception             ' Display the error message to the reader.             ErrorMessage.Text = ex.Message.ToString()         Finally             ' See if the connection is open.             If objConnection.State = ConnectionState.Open Then                 ' Close it if it is open.                 objConnection.Close()             End If         End Try     End If End Sub 

As with the Page_Load() method for the Repeater demo, this code performs a pretty straightforward retrieval of data with which the Repeater is bound. First, a connection to the database is created by creating a SqlConnection object and then calling its Open() method. Any code that can throw an exception is within a try block. The try/catch/finally construct allows the code to be robust and handle any errors that might arise. If everything goes well, all of the code in the try block is executed, followed by the code in the finally block. If an exception is thrown at any point in the try block, execution proceeds to the catch block, after which the finally block will be executed.

Once the connection has been established to the database, a SqlCommand object must be created. This gives us the capability to execute a query on the database and get a recordset back. The recordset will be contained in a SqlDataReader object. The following SQL will be executed:

 SELECT lname,fname,hire_date FROM employee ORDER BY lname,fname 

A call to the SqlCommand.ExecuteReader() method returns a populated SqlDataReader object. The Repeater is now bound to the data by setting the DataGrid.DataSource property to the SqlDataReader, and then calling the DataGrid.DataBind() method.

The Employees_SelectedIndexChanged() Method of the DataGrid Demo

The code for the Employees_SelectedIndexChanged() method follows. It is fired when users click on the Send button. A discussion of the code is immediately below it.

C#
 private void Employees_SelectedIndexChanged(object sender, System.EventArgs e) {   // Get the employee name.   string strName =    ((Label)Employees.Items[Employees.SelectedIndex].FindControl(    "Name")).Text;   // Create the message body.   string strMessage = "This is a message that was sent by " +     "the DataGrid demo program. The employee that is being " +     "referred to is " + strName;   try   {     // Send the email.     SmtpMail.SmtpServer = "mail.server.com";     SmtpMail.Send( "DataGrid Demo <Joe@server.com>",       Email.Text, "Notification about employee", strMessage );     // Alert the user to the success.     ErrorMessage.Text = "Your message was sent at " +       Convert.ToString( DateTime.Now );   }   catch( Exception ex )   {     ErrorMessage.Text = ex.Message.ToString();   } } 
VB
 Private Sub Employees_SelectedIndexChanged(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles Employees.SelectedIndexChanged     ' Get the employee name.     Dim Name As Label = _       Employees.Items(Employees.SelectedIndex).FindControl("Name")     Dim strName As String = Name.Text     ' Create the message body.     Dim strMessage as String = "This is a message that was sent by " + _        "the DataGrid demo program. The employee that is being " + _        "referred to is " + strName     Try         ' Send the email.         SmtpMail.SmtpServer = "mail.server.com"         SmtpMail.Send("DataGrid Demo <Joe@server.com>", _          Email.Text, "Notification about employee", strMessage)         ' Alert the user to the success.         ErrorMessage.Text = "Your message was sent at " + _           Convert.ToString( DateTime.Now )     Catch ex As Exception         ErrorMessage.Text = ex.Message.ToString()     End Try End Sub 

The Employees_SelectedIndexChanged() method starts off by retrieving the e-mail address that the user (hopefully) typed in the e-mail TextBox. The next thing it does is to create the message text for the e-mail. The employee name is used in the creation of the message body.

Next, the SmtpMail class is used to send an e-mail message. I should point out that, technically, setting the SmtpServer property isn't necessary. Where this is important, though, is in the security restrictions of most mail servers. On my network, without setting this to our mail server, the e-mails could not be delivered.

Finally, if everything goes well, the user is alerted to the successful sending of the e-mail message. Notice, though, that the SmtpMail code is within a Try/Catch construct. That's because SmtpMail code can throw an exception. You can see the demo after an e-mail has been sent in Figure 6.7.

Figure 6.7. This Part of the Application Sends E-mails.

graphics/06fig07.jpg



ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ISBN: 321159659
EAN: N/A
Year: 2003
Pages: 175

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