An Extensive Examination of the DataGrid WebControl
Jetpak is Public
Created By: travislaborde
Last Modified: 05/12/06
Summary: By Scott Mitchell

n Extensive Examination of the DataGrid Web Control: Part 3
By Scott Mitchell


The Third Part in a Multi-Part Series
This article is the third piece of a multi-part series on using the DataGrid Web control that will span several weeks. The ASP.NET DataGrid Web control, which displays database information in an HTML table, is highly versatile. The basics of the DataGrid were discussed in Part 1; information on specifying display properties of the DataGrid was discussed in Part 2. This article will examine how to associate custom events with the DataGrid.

  • Read Part 4
  • Read Part 5
  • Read Part 6
  • Read Part 7
  • Read Part 8
  • Read Part 9
  • Read Part 10
  • Read Part 11
  • Read Part 13
  • Read Part 14
  • Read Part 15
  • Read Part 16
  • Read Part 17
  • Read Part 18
  • ASP.NET Data Web Controls Kick Start

    ASP.NET Data Web Controls Kick Start

    ASP.NET Data Web Controls Kick Start is author Scott Mitchell's most recent book, which thoroughly examines three of the most commonly used ASP.NET Web controls: the DataGrid, DataList, and Repeater. These three Web controls can be difficult to master due to their numerous features and capabilities. With this book, you'll quickly become an expert, learning the gritty details and true capabilities of each. This 400+ page book explores the topics in this article series in much greater depth, along with examining various topics and techniques not covered here.

    Scott Mitchell is the editor and founder of 4GuysFromRolla.com, author of the An Extensive Examination of the DataGrid Web Control article series, and author of numerous other ASP and ASP.NET books.

    [Buy this Book]
    [Visit the Book's Companion Web Site]

    Introduction
    In Part 1 we examined the elementary basics of the DataGrid, an ASP.NET Web control designed to display data in an HTML table tag, showing how simple it was to display database contents through an ASP.NET Web page. Part 2 examined how to customize the look of the resulting DataGrid. As we saw in a live demo, with very little programmatic code we could display database information in a very impressive format.

    While displaying data is nice and all, what would really be useful is if we could associate some sort of action with the DataGrid. For example, imagine that we worked for some eCommerce firm and were asked to display a DataGrid showing the data for the list of all orders. Each order might have a large amount of data associated with it, including the item purchased, the date purchased, information about the buyer (name, address, etc.), what shipping options the buyer chose, etc. Showing all of this information in a single DataGrid (for every order) would be information overload.

    As we saw in Part 2, we could use simply set AutoGenerateColumns to False and then use the Columns property to specify what columns from the order information we wanted to display. While this would make the data easier to digest, what if the user wanted to also have the option to view the intricate details of any particular order? Ideally we'd like to be able to have on each row in the DataGrid a button labeled "Details" that, when clicked, would display the complete information for that particular order.

    The live demos in this article step through a very similar application. In our previous live demos we were displaying the top 10 most popular FAQs from ASPFAQs.com. In this article we'll extend the live demo to show only the most important information for each of the 10 most popular FAQs along with a "Details" button. When the "Details" button is clicked, the user will see all of the information for the FAQ they clicked the "Details" button on.

    Building on a Foundation
    As we saw in Part 2, the DataGrid control allows for a number of BoundColumn tags in the Columns tag of the DataGrid control. Recall that each BoundColumn tag represents a column in the resulting DataGrid. To place a button in the DataGrid we can use the ButtonColumn tag much in the same way as we used the BoundColumn tags. The following source code shows how to place a button in a DataGrid:

    [View a live demo!]

    Note that to get this to work we needed to place the DataGrid within a server-side form (the bolded

    shown above). This is because in order to track the button that was clicked and the associated action that should occur, the ASP.NET page needs to be able to reconstruct the page and series of buttons in the DataGrid. To do this it needs the page's ViewState. A thorough discussion of ViewState is beyond the scope of this article; for more information read: Form Viewstate.

    Note that the button created by the live demo is a textual link button. This is the default appearance generated by the ButtonColumn class. If you want to display a standard button, you can simply specify: ButtonType="PushButton" in the ButtonColumn tag. The ButtonColumn class has a number of important properties. Two of the stylistic ones are used in the code sample above. HeaderText specifies the text that should go in the header of the DataGrid's column in which the button appears; Text specifies the textual display for each button. As with the BoundColumn tag, the ButtonColumn tag can have each button's text be the value of some column in the DataGrid's DataSource - simply omit the Text property in the ButtonColumn class and set the DataTextField property to the name of the database column whose value you wish to have displayed as the button's text.

    Having Something Happen When the Button is Clicked
    Now that we have a button in our DataGrid, we'd like to be able to associate some server-side code with the button so that, when it's clicked, some action can take place. Realize that whenever a ButtonColumn button in the DataGrid is clicked, the ItemCommand event is fired; hence, we can write a server-side event-handler for this event. This event handler must have the following definition:

    Sub eventHandlerName(sender as Object, e as DataGridCommandEventArgs)
       ...
    End Sub

    Once you define this function in your server-side script block (or code-behind page) you can tie the actual DataGrid event to this event handler by adding the OnItemCommand property in the DataGrid's tag, like so:

          ...
          OnItemCommand="eventHandlerName">
       ...

    The following code demonstrates how to have an event handler run when one of the buttons in the DataGrid is clicked:

    
    
    
      
        ...
      
    
    
    [View a live demo!]

    There is one very important thing to notice here: we are only performing our database query and databinding to the DataGrid on the first page visit. In our Page_Load event handler, which fires every time the page is loaded, we check to see if the page has been posted back. If it has not, then we know this is the first visit to the page. In this case we want to populate a DataReader with a database query, set the DataGrid's DataSource property to this DataReader, and call the DataGrid's DataBind() method.

    When the person clicks one of the "Details" buttons in the DataGrid, the ASP.NET Web page will perform a postback, making a round trip back to the server. Again, the Page_Load event handler will fire, but this time, since we're doing a postback, the BindData() Sub will not be called. Furthermore, the detailsClicked event handler will execute. Note that if we blindly rebind the data to the DataGrid (that is we omit the If Not Page.IsPostBack check) the detailsClicked event handler will not run, since rebinding of the DataGrid flushes out the ItemCommand event. (Please reread the above two paragraphs - chances are at some point in your experiences with the DataGrid you'll forget to do this and won't be able to get the DataGrid to fire event handler code for its buttons. Trust me, it's happened to me a couple of times! :-).)

    While this example and live demo illustrate how to have an event handler associated with a button click from a ButtonColumn tag, we've yet to see how one can determine what row of the DataGrid had its button clicked. This very important question will be examined in Part 2 of this article.


    From: http://aspnet.4guysfromrolla.com/articles/042402-1.aspx

    An Extensive Examination of the DataGrid Web Control: Part 2
    By Scott Mitchell


    The Second in a Multi-Part Series
    This article is the second piece of a multi-part series on using the DataGrid Web control that will span several weeks. The ASP.NET DataGrid Web control, which displays database information in an HTML table, is highly versatile. The basics of the DataGrid were discussed in Part 1. This article will examine how to perform custom formatting of the DataGrid.
  • Read Part 3
  • Read Part 4
  • Read Part 5
  • Read Part 6
  • Read Part 7
  • Read Part 8
  • Read Part 9
  • Read Part 10
  • Read Part 11
  • Read Part 12
  • Read Part 13
  • Read Part 14
  • Read Part 15
  • Read Part 16
  • Read Part 17
  • Read Part 18
  • ASP.NET Data Web Controls Kick Start

    ASP.NET Data Web Controls Kick Start

    ASP.NET Data Web Controls Kick Start is author Scott Mitchell's most recent book, which thoroughly examines three of the most commonly used ASP.NET Web controls: the DataGrid, DataList, and Repeater. These three Web controls can be difficult to master due to their numerous features and capabilities. With this book, you'll quickly become an expert, learning the gritty details and true capabilities of each. This 400+ page book explores the topics in this article series in much greater depth, along with examining various topics and techniques not covered here.

    Scott Mitchell is the editor and founder of 4GuysFromRolla.com, author of the An Extensive Examination of the DataGrid Web Control article series, and author of numerous other ASP and ASP.NET books.

    [Buy this Book]
    [Visit the Book's Companion Web Site]

    Introduction
    In
    Part 1 we examined the elementary basics of the DataGrid, an ASP.NET Web control designed to display data in an HTML table tag. Part 1 illustrates how simple it was to bind database contents to a DataGrid: all we needed to do was populate a DataReader object with a SQL query, set the DataReader to the DataGrid's DataSource property, and then call the DataGrid's DataBind() method. All that was left was to place the DataGrid Web control in the HTML content, which could be done with:

    Pretty simple. Unfortunately this simple approach renders a fairly ugly DataGrid. As we saw from this live demo, the resulting DataGrid is little more than a vanilla HTML table encapsulating all of the columns and rows present in the DataReader.

    What we'd like to be able to do is display only certain columns from the DataReader, and specify each column's format. Also, we'd like to be able to specify some table-wide formatting settings, such as the background color, the font, etc. Finally, it would be nice to be able to add some custom headings for each column, perhaps giving the heading a different background color or a bolded font. In this part we'll examine how to do all of these tasks! (The DataGrid can do so much more, as we'll see in future parts to this article series, such as paging through database results, allowing users to sort the data, etc. These topics are for a future article, though!)

    Specifying DataGrid Formatting Options
    We have two options on how to specify formatting options for a DataGrid. The first option is to set the setting programmatically in the server-side script block. For example, to set the background color of the DataGrid to red you could use the following server-side code:

    <%@ Import Namespace="System.Drawing" %>
    
    
    

    The other method you can use to set display properties is to specify them in the DataGrid Web control tag. For example, the following code has the same effect as the above code:

    Personally I prefer the latter method. I find specifying the display properties in the Web control tag itself to be cleaner than the server-side code alternative. (For the server-side code approach note that we needed to import the System.Drawing namespace and refer to the color as Color.Red; with specifying the display properties in the Web control tag we just needed to say BackColor="Red". I find this saving of typing to be more readable.)

    Let's look at some of the useful formatting settings we can apply to our DataGrid. The ones I think you'll find most useful are:

    • BackColor - specifies the background color.
    • Font - specifies the font information for the DataGrid. Font information includes things like the font family, the point size, if its bold, italicized, etc.
    • CellPadding - specifies the cellpadding of the HTML table
    • CellSpacing - specifies the cellspacing of the HTML table
    • Width - specifies the width of the HTML table (can be in pixels, percentages, etc.)
    • HorizontalAlign - specifies how the table should be aligned (Left, Right, Center, NotSet)
    An example of using these display preference properties to create a nicer looking DataGrid can be seen below. Note that the Font property of the DataGrid is, in actuality, an object reference to the FontInfo class, which contains properties like Size, Name, Bold, Italic, etc. In order to set a property of one of the classes represented by the Font we have to use a hyphen (-). This is synonymous to the "dot" in languages like VB.NET and C# when referencing an object's property.

    
    
    [View a live demo!]

    Pretty impressive, eh? With just a few lines of text we greatly improved the UI of our DataGrid. We went from a vanilla HTML table to a centered one with a gray background color and a nice-looking font.

    Getting Fancy with Styles
    The DataGrid Web control contains a number of "styles" that you will find quite useful in customizing the look and feel of the DataGrid. These styles can support a number of stylistic properties such as: BackColor, ForeColor, Font, HorizontalAlign, and Width, to name the most useful ones. (See the docs for more information.) There are four available styles in DataGrids:

    • HeaderStyle - Specifies the style information for the header (the top row of the table that lists the column names; you must have the DataGrid's ShowHeader property set to true (the default).)
    • FooterStyle - Specifies the style information for the footer (the bottom row of the table that lists the column names; you must have the DataGrid's ShowFooter property set to true (the default is false).)
    • ItemStyle - Specifies the style information for each row in the table.
    • AlternatingItemStyle - Specifies the style information for alternate rows in the table. You can set the ItemStyle and AlternatingItemStyle to different values for an easier-to-read DataGrid (see the below demo for an example).

    Like other DataGrid formatting properties, the styles can be set either programmatically or through the DataGrid's Web control tags. As aforementioned, I prefer the Web control tag approach and will stick to that for this example. There are two ways to set the style properties through the Web control tag syntax. The first is similar to the way we've been specifying properties that were, in actually, objects, by using the dash (i.e., to set the BackColor for the HeaderStyle you could do: HeaderStyle.BackColor="Red")

    Another approach is to use special style blocks within the definition of the Web control tag, like so:

    
      
    
    

    Either way is fine. I find using the embedded tags helps in readability, especially when you plan on setting a lot of properties for a lot of styles. The following example shows how to pretty-up our earlier example:

    
      
      
    
    
    [View a live demo!]

    Now that we've examined how to integrate stylistic features and how to set global display properties for a DataGrid control, we've got one topic left for this part of the article series: how to customize the formatting and style for each specific column in the DataGrid. More on this technique in Part 2 of this article!


    From: http://aspnet.4guysfromrolla.com/articles/041702-1.aspx

    An Extensive Examination of the DataGrid Web Control: Part 1
    By Scott Mitchell


    The First in a Multi-Part Series
    This article is the first in a multi-part series on using the DataGrid Web control that will span several weeks. The ASP.NET DataGrid Web control, which displays database information in an HTML table, is highly versitile. In its simplest form (examined in this article) the DataGrid displays a bare-bones HTML table, but it can be enhanced to output a richer UI, to allow for sorting based on the database columns, and to even allow paging of the database results! All of these interesting topics will be covered in future parts of this article series.

  • Read Part 2
  • Read Part 3
  • Read Part 4
  • Read Part 5
  • Read Part 6
  • Read Part 7
  • Read Part 8
  • Read Part 9
  • Read Part 10
  • Read Part 11
  • Read Part 12
  • Read Part 13
  • Read Part 14
  • Read Part 15
  • Read Part 16
  • Read Part 17
  • Read Part 18
  • Introduction
    One of the most common tasks in classic ASP was retrieving tabular information from a database and displaying it in an HTML table. With classic ASP this would require many lines of intermixed HTML and code; the following pseudocode shows what the code would commonly look like:

    Create Database Connection
    Populate a recordset based on some SQL query
    Output the HTML table header ()
    Loop through the recordset
      Emit the HTML for a table row
      ...
    Emit the HTML table footer (
    )

    If you're an ASP developer chances are you've written code like above more times than you'd care to admit! One of the advantages of ASP.NET is that it contains a number of Web controls. These Web controls, which emit HTML, provide a programmatic interface, allowing developers to separate code and content and treat these HTML emitting entities as objects in their code. That is, if we wanted to display some HTML content using ASP.NET we'd do the following:

    
    
    
    

    Here the label Web control lblMessage is placed in the HTML using HTML-like tags with the runat="server" attribute specified. Then, in the Page_Load event handler (which is run every time the page is loaded) the Text property of the lblMessage Web control is set to "Hello, World!" The use of Web controls here separates the code from the content; in classic ASP one would need to place a <%="Hello, World!"%> in the proper place within the HTML content to achieve the same effect.

    There are ASP.NET Web controls that are much more useful and powerful than the simple label control. The DataGrid Web control, which we'll be dissecting in this article, is one such powerful control. The DataGrid emits the needed HTML for data-bound HTML tables. As we'll soon see, binding data to a DataGrid is very easy; furthermore, with only a few slight property changes you can customize the look and feel the DataGrid's output, rendering very professional looking HTML tables (a feat when one considers my utter lack of artistic skill!).

    DataGrid Basics
    To place a DataGrid on an ASP.NET Web page you simply need to add the following code:

    Here the id you choose will be the name of the DataGrid you'll use when referring to it in your server-side code. The syntax above gets us started using a DataGrid by placing it in the HTML content, but in order to have the DataGrid display anything useful we need to bind the DataGrid to some collection of information. This collection of information can be any object that supports the IEnumerable interface. This includes things like Arrays, collection classes (ArrayList, Hashtable, etc.), DataSets, DataReaders, and a number of other objects. Since we'd like to focus on displaying database information, for this article we'll focus on binding DataGrids to DataReaders, which are synonymous to forward-only, firehose cursors Recordsets in classic ADO/ASP. (For more information on reading database results into DataReaders using ADO.NET be sure to read: Efficiently Iterating Through Results from a Database Query using ADO.NET.)

    So, how do we go about binding data to the DataGrid? It's amazingly simple. The first thing we need to do is to grab a DataReader containing some database data. For this example I am hitting the ASPFAQs.com database and bringing back the ten most popular FAQs. Once I have this data in a DataReader, to bind it to my DataGrid I just need to write two lines of code. The first line sets the DataGrid's DataSource property to the DataReader; the second line calls the DataGrid's DataBind method. That's all there is to it, as the following code snippet shows.

    <% @Import Namespace="System.Data" %>
    <% @Import Namespace="System.Data.SqlClient" %>
    
    
    
    
    [View a live demo!]

    First off note that the amount of code we have to write to utilize databinding is not much at all. We essentially create a connection, specify a SQL command (in this case a stored procedure, sp_Popularity), open the database connection, set the DataGrid's DataSource property to the resulting DataReader, and finally call the DataGrid's DataBind method. This approach completely isolates the code from the content; there's no mixing of HTML table and DataReader output syntax, as we would have had with classic ASP.

    Take a moment to view the live demo. You'll notice that the DataGrid displays the database contents in a plane-Jane HTML table - it's pretty ugly. While the main "work" has been done for us (displaying the data), there's a lot to be desired on the user-interface front. Fortunately, prettying up the DataGrid results is amazingly easy. Unfortunately, this will have to wait for the next part of this article series! Stay tuned! :-)

    Summary
    In this part of the series on DataGrid usage, we examined the very basics of DataGrids - how to plop one down on an ASP.NET Web page and display bound database results. Unfortunately the DataGrid's output is not pretty. However, as we'll soon see, prettying up the display of the DataGrid is a breeze. Additionally, we'll look at more advanced UI options (such as paging database results, sorting the DataGrid's results on the fly, and other cool stuff) in upcoming portions of this article.

    Happy Programming!

  • By Scott Mitchell

  • From: http://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/040502-1.aspx



    ADVERTISING