Chapter 16


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Chapter 16

  1. 1. In this chapter, you’ll concentrate on threemore advanced controls that allow you tobind entire tables of data.• GridView• Details View• FormView
  2. 2. 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.•
  3. 3. 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();}
  4. 4. 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" />
  5. 5. 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.
  6. 6. 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
  7. 7. 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}" />
  8. 8. 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;}}}
  9. 9. 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" />
  10. 10. 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" />
  11. 11. 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.
  12. 12. 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.
  13. 13. 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“ />
  14. 14. <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>
  15. 15. 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
  16. 16. 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" />
  17. 17. 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" />