chapter 16

20
Data Controls In this chapter, you’ll concentrate on three more advanced controls that allow you to bind entire tables of data. • GridView Details View • FormView

Upload: application-developer

Post on 03-Dec-2014

1.008 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Chapter 16

Data Controls

In this chapter, you’ll concentrate on three more advanced controls that allow you to bind entire tables of data.

• GridView

• Details View

• FormView

Page 2: Chapter 16

Data Controls

GridView: The GridView is an all-purpose grid control for showing large tables of information. it comes equipped with the most ready-made functionality like sorting, paging, selecting, editing and deleting. DetailsView: The DetailsView is ideal for showing a single record at a time. The DetailsView also supports editing.

FormView: Like the DetailsView, the FormView shows a single record at a time and supports editing. The difference is that the FormView is based on templates, which allow you to combine fields in a flexible layout that doesn’t need to be table-based.•

Page 3: Chapter 16

Bind Dataset with a GridView

protected void Page_Load(object sender, EventArgs e){string connectionString =WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;

string selectSQL = "SELECT ProductID, ProductName, UnitPrice FROM 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();}

Page 4: Chapter 16

Simplifying the previous code

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, UnitPrice FROM Products" />

Next, set the GridView.DataSourceID property to link the data source to your grid:

<asp:GridView ID="GridView1" runat="server"DataSourceID="sourceProducts" />

Page 5: Chapter 16

Defining Columns

By default, the GridView.AutoGenerateColumns property is true, and the GridView creates a column for each field in the bound DataTable.

This automatic column generation is good for creating quick test pages, but it doesn’t give you the flexibility you’ll usually want. For example, what if you want to hidecolumns, change their order, or configure some aspect of their display, such as the formatting or heading text?

In all these cases, you need to set AutoGenerateColumns to false and define the columns in the <Columns> section of the GridView control tag.

Page 6: Chapter 16

Types of Columns in a GridView

Page 7: Chapter 16

Features of a GridView

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 and respond accordinglyEditing: How to let users commit record updates, inserts, and deletesSorting: How to dynamically reorder the GridView in response to clicks on a column headerPaging: How to divide a large result set into multiple pages of dataTemplates: How to take complete control of designing, formatting, and editing by defining templates

Page 8: Chapter 16

Formatting the GridView

You handle this job with the DataFormatString property.

Each BoundField column provides a DataFormatString property you can use to configure the appearance of numbers 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}" />

Page 9: Chapter 16

Using Styles

Page 10: Chapter 16

Formatting-Specific Values

protected void GridView1_RowDataBound(object sender, 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;}}}

Page 11: Chapter 16

Selecting a GridView Row

The GridView provides built-in support for selection. You simply need to add a CommandField column with the ShowSelectButton property set to true.

ASP.NET can render the CommandField as a hyperlink, a button, or a fixed image.

<asp:CommandField ShowSelectButton="True" ButtonType="Button“ SelectText="Select" />

<asp:CommandField ShowSelectButton="True" ButtonType="Image“ SelectImageUrl="select.gif" />

Page 12: Chapter 16

Using a Data Field As a Select Button

You don’t need to create a new column to support row selection. Instead, you can turn an existing column into a link.

<asp:ButtonField CommandName="Select" ButtonType="Button"DataTextField="ProductID" />

Page 13: Chapter 16

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, the second GridView is filled with related records from the details (or parent) table.

Using Selection to Create Master-Details Pages

Page 14: Chapter 16

Use the CommandField column, set ShowEditButton to true.

Editing with the GridView

Sorting and Paging the GridView

To enable sorting, you must set the GridView.AllowSorting property to true. Next, you need to define a SortExpression for each column that can be sorted.

To use automatic paging, you need to set AllowPaging to true (which shows the page controls), and you need to set PageSize to determine how many rows are allowed on each page.

Page 15: Chapter 16

You can use each SqlDataSource control you create, to retrieve a single query.

The SqlDataSource command logic is supplied through four properties—SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand—each of which takes a string.

<asp:SqlDataSource ID="sourceProducts" runat="server"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT ProductName, ProductID FROM Products“ />

Selecting Records

Page 16: Chapter 16

<asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>“

SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID"/>

<asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID">

<SelectParameters><asp:ControlParameter ControlID="lstProduct" Name="ProductID"PropertyName="SelectedValue" /></SelectParameters></asp:SqlDataSource>

Parameterized Commands

Page 17: Chapter 16

If bound to Rich Controls SqlDataSource can display many fields at a time as compared to List Controls which display only one field at a time.

Example:

GridviewDetailsView

Bind SqlDataSource to Rich Controls

Page 18: Chapter 16

Other Types of Parameters

Page 19: Chapter 16

For example, you could split the earlier example into two pages. In the first page, 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" />

Using QueryStringParameter

Page 20: Chapter 16

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 value that’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" />

Using QueryStringParameter