Chapter 16
Upcoming SlideShare
Loading in...5
×
 

Chapter 16

on

  • 953 views

 

Statistics

Views

Total Views
953
Views on SlideShare
953
Embed Views
0

Actions

Likes
0
Downloads
25
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Chapter 16 Chapter 16 Presentation Transcript

  • In this chapter, you’ll concentrate on threemore advanced controls that allow you tobind entire tables of data.• GridView• Details View• FormView
  • GridView: The GridView is an all-purpose grid control forshowing large tables of information. it comes equippedwith the most ready-made functionality like sorting,paging, selecting, editing and deleting.DetailsView: The DetailsView is ideal for showing asingle record at a time. The DetailsView also supportsediting.FormView: Like the DetailsView, the FormView shows asingle record at a time and supports editing. Thedifference is that the FormView is based on templates,which allow you to combine fields in a flexible layout thatdoesn’t need to be table-based.•
  • protected void Page_Load(object sender, EventArgs e){string connectionString =WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;string selectSQL = "SELECT ProductID, ProductName, UnitPriceFROM Products";SqlConnection con = new SqlConnection(connectionString);SqlCommand cmd = new SqlCommand(selectSQL, con);SqlDataAdapter adapter = new SqlDataAdapter(cmd);DataSet ds = new DataSet();adapter.Fill(ds, "Products");GridView1.DataSource = ds;GridView1.DataBind();}
  • Of course, you don’t need to write this data access code by hand.Define a SqlDataSource to perform the query shown in the previousexample:<asp:SqlDataSource ID="sourceProducts" runat="server"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT ProductID, ProductName, UnitPriceFROM Products" />Next, set the GridView.DataSourceID property to link the data sourceto your grid:<asp:GridView ID="GridView1" runat="server"DataSourceID="sourceProducts" />
  • By default, the GridView.AutoGenerateColumns propertyis true, and the GridView creates a column for each fieldin the bound DataTable.This automatic column generation is good for creatingquick test pages, but it doesn’t give you the flexibility you’llusually want. For example, what if you want to hidecolumns, change their order, or configure some aspect oftheir display, such as the formatting or heading text?In all these cases, you need to set AutoGenerateColumnsto false and define the columns in the <Columns> sectionof the GridView control tag.
  • Now that you understand the underpinnings of the GridView,you’ve still only started to explore its higher-level features.Formatting: How to format rows and data valuesSelecting: How to let users select a row in the GridView andrespond accordinglyEditing: How to let users commit record updates, inserts,and deletesSorting: How to dynamically reorder the GridView inresponse to clicks on a column headerPaging: How to divide a large result set into multiple pagesof dataTemplates: How to take complete control of designing,formatting, and editing by defining templates
  • You handle this job with the DataFormatString property.Each BoundField column provides a DataFormatStringproperty you can use to configure the appearance ofnumbers and dates using a format string.<asp:BoundField DataField="UnitPrice"HeaderText="Price"DataFormatString="{0:C}" /><asp:BoundField DataField="BirthDate"HeaderText="Birth Date"DataFormatString="{0:MM/dd/yy}" />
  • protected void GridView1_RowDataBound(objectsender, GridViewRowEventArgs e){if (e.Row.RowType == DataControlRowType.DataRow){// Get the price for this row.decimal price =(decimal)DataBinder.Eval(e.Row.DataItem, "UnitPrice");if (price > 50){e.Row.BackColor = System.Drawing.Color.Maroon;e.Row.ForeColor = System.Drawing.Color.White;e.Row.Font.Bold = true;}}}
  • The GridView provides built-in support for selection. Yousimply need to add a CommandField column with theShowSelectButton property set to true.ASP.NET can render the CommandField as a hyperlink, abutton, or a fixed image.<asp:CommandField ShowSelectButton="True"ButtonType="Button“ SelectText="Select" /><asp:CommandField ShowSelectButton="True"ButtonType="Image“ SelectImageUrl="select.gif" />
  • You don’t need to create a new column to supportrow selection. Instead, you can turn an existingcolumn into a link.<asp:ButtonField CommandName="Select"ButtonType="Button"DataTextField="ProductID" />
  • A typical master-details page has two GridView controls.The first GridView shows the master (or parent) table.When a user selects an item in the first GridView, thesecond GridView is filled with related records from thedetails (or parent) table.
  • Use the CommandField column, set ShowEditButton to true.To enable sorting, you must set the GridView.AllowSortingproperty to true. Next, you need to define a SortExpressionfor each column that can be sorted.To use automatic paging, you need to set AllowPaging totrue (which shows the page controls), and you need to setPageSize to determine how many rows are allowed oneach page.
  • You can use each SqlDataSource control you create,to retrieve a single query.The SqlDataSource command logic is supplied throughfour properties—SelectCommand, InsertCommand,UpdateCommand, and DeleteCommand—each of whichtakes a string.<asp:SqlDataSource ID="sourceProducts" runat="server"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT ProductName, ProductIDFROM Products“ />
  • <asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>“SelectCommand="SELECT * FROM Products WHEREProductID=@ProductID"/><asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT * FROM Products WHEREProductID=@ProductID"><SelectParameters><asp:ControlParameter ControlID="lstProduct" Name="ProductID"PropertyName="SelectedValue" /></SelectParameters></asp:SqlDataSource>
  • If bound to Rich Controls SqlDataSource can displaymany fields at a time as compared to List Controls whichdisplay only one field at a time.Example:GridviewDetailsView
  • For example, you could split the earlier example into two pages. In the firstpage, define a list control that shows all the available products:<asp:SqlDataSource ID="sourceProducts" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT ProductName, ProductID FROM Products"/><asp:DropDownList ID="lstProduct" runat="server" AutoPostBack="True"DataSourceID="sourceProducts" DataTextField="ProductName"DataValueField="ProductID" />
  • protected void cmdGo_Click(object sender, EventArgs e){if (lstProduct.SelectedIndex != -1){Response.Redirect("QueryParameter2.aspx?prodID=" + lstProduct.SelectedValue);}}Finally, the second page can bind the DetailsView according to the ProductID valuethat’s supplied in the query string:<asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID"><SelectParameters><asp:QueryStringParameter Name="ProductID" QueryStringField="prodID" /></SelectParameters></asp:SqlDataSource><asp:DetailsView ID="detailsProduct" runat="server"DataSourceID="sourceProductDetails" />