03.11.2016 Views

Beginning ASP.NET 4.5 in CSharp and VB Opsylum

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

572 x CHAPTER 15 WORKING WITH DATA — ADVANCED TOPICS<br />

How It Works<br />

Although short, this exercise demonstrates a powerful way to hook <strong>in</strong>to the different events of a control<br />

<strong>and</strong> change the presentation of the underly<strong>in</strong>g control. To see how it works, take a look at the modified<br />

SQL code first:<br />

SELECT<br />

Genre.Id, Genre.Name, Genre.SortOrder, COUNT(Review.Id) AS NumberOfReviews<br />

FROM<br />

Genre LEFT OUTER JOIN<br />

Review ON Genre.Id = Review.GenreId<br />

GROUP BY<br />

Genre.Id, Genre.Name, Genre.SortOrder<br />

This modified SQL statement gets all the columns from<br />

the Genre table but <strong>in</strong>troduces a new column, called<br />

NumberOfReviews, which conta<strong>in</strong>s the number of reviews<br />

associated with each genre. It does this by execut<strong>in</strong>g the SQL<br />

COUNT function aga<strong>in</strong>st the Id column of the Review table.<br />

The statement uses GROUP BY to group the selected rows <strong>in</strong>to a<br />

set of summary rows by collaps<strong>in</strong>g non-unique rows. Because<br />

the SQL statement is grouped on all unique columns <strong>in</strong> the<br />

Genre table, you get a unique row <strong>in</strong>clud<strong>in</strong>g the number of<br />

reviews for each genre row, whether or not reviews are associated,<br />

as shown <strong>in</strong> Figure 15-9, which displays the result of this<br />

query <strong>in</strong> SSMS.<br />

When this query is executed, the GridView <strong>in</strong> the markup of FIGURE 15-9<br />

the page makes use of the first three columns, just as it did <strong>in</strong><br />

the previous version of this page. But you can access the fourth column as well. You do this <strong>in</strong> the Code<br />

Beh<strong>in</strong>d, <strong>in</strong> the RowDataBound event to be exact, which fires for each row after the GridView is done<br />

b<strong>in</strong>d<strong>in</strong>g the data for a specific row:<br />

<strong>VB</strong>.<strong>NET</strong><br />

Protected Sub GridView1_RowDataBound(sender As Object,<br />

e As GridViewRowEventArgs) H<strong>and</strong>les GridView1.RowDataBound<br />

Select Case e.Row.RowType<br />

Case DataControlRowType.DataRow<br />

...<br />

End Select<br />

End Sub<br />

C#<br />

protected void GridView1_RowDataBound (object sender, GridViewRowEventArgs e)<br />

{<br />

switch (e.Row.RowType)<br />

{<br />

case DataControlRowType.DataRow:<br />

...<br />

}<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!