Manipulating data in ASP.net 2.0 27: Creating a custom Sort user interface _ self-study process

Source: Internet
Author: User

Brief introduction

Displaying a large number of data that has been sorted by category (not many) but without a category boundary makes it difficult for users to find the category they need. For example, there are only 9 categories in the database (8 different categories and one null), A total of 81 products. Now list all the products with a GridView, assuming that there are users interested in the category Seafood products, she will be sorted by category, the seafood products are arranged together. After sorting, the user then looks for the place where the seafood product begins and ends. Although the alphabetical category is not hard to find seafood, it still takes some time to search the GridView. To further differentiate categories, many sites use the category dividing line to differentiate between different categories of this sort user interface. For example, the line in Figure 1 allows the user to quickly find the desired category.

Figure 1: Distinct groups are clearly distinguished

In this article we will explain how to create this sort user interface.

Step 1: Create an ordinary, able to sort the GridView

Before we learn how to create an enhanced sort user interface, we first create a generic list of all the product GridView and be able to sort. Now hit the customsortingui.aspx in the PagingAndSorting folder, add a GridView, Set the id= "ProductList" to a ObjectDataSource as a data source, ObjectDataSource data from PRODUCTSBLL ().

Next, set the columns for the GridView, including ProductName, CategoryName, SupplierName, UnitPrice bound columns, and Discontinued check box columns, and then set the GridView to allow sorting. After setting these up you should be able to see the following code in the Code Editor:

<asp:gridview id= "productlist" runat= "Server" allowsorting= "True" autogeneratecolumns= "False" datakeynames= " ProductID "datasourceid=" ObjectDataSource1 "enableviewstate=" False "> <Columns> <asp:boundfield Datafield= "ProductName" headertext= "Product" sortexpression= "ProductName"/> <asp:boundfield "datafield=" CategoryName "headertext=" Category "readonly=" True "sortexpression=" CategoryName "/>" <asp:boundfield DataField = "SupplierName" headertext= "Supplier" readonly= "True" sortexpression= "SupplierName"/> <asp:boundfield Datafield= "UnitPrice" dataformatstring= "{0:c}" headertext= "Price" htmlencode= "False" sortexpression= "UnitPrice"/
 > <asp:checkboxfield datafield= "Discontinued" headertext= "discontinued" sortexpression= "Discontinued"/> </Columns> </asp:GridView> <asp:objectdatasource id= "ObjectDataSource1" runat= "Server" oldvaluesparameterformatstring= "original_{0}" selectmethod= "GetProducts" typename= "ProductsBLL" ></asp:ObjectDataSource>
 

When you preview in the browser you will see an interface similar to Figure 2, sorted alphabetically by category.

Figure 2: The sortable GridView Press category to order

Step 2: How to add a boundary line

When you are done creating an ordinary, sortable GridView, you add the demarcation line before the first row of each category. How do you add these lines to the GridView? At first we thought of traversing all the rows of the GridView and inserting the demarcation line when the values in the row sequence were different. In this way, we naturally want to use the Datarowbound event of the GridView, Datarowbound events we have already mentioned in the chapter on custom formatting based on data, datarowbound events are usually applied to formatting rows of data. However, the Datarowbound event does not solve the problem because the rows to Gridview,gridview row collection that cannot be dynamically added with this event is read-only.

There are 3 ways to add rows to the GridView:

Add demarcation lines to the data source of the GridView binding
After the GridView binds the data, add the additional TableRow object to the control set of the GridView
Create a custom server control, extend the GridView control, override its methods to reconstruct the structure of the GridView

Creating a custom server control is the best approach if you have a custom sort user interface that uses a wide range of pages or multiple Web sites. But in this way you write too much code and have a deep understanding of the inner workings of the GridView control. Therefore, we do not consider using this method in this article. The other two different methods-adding a demarcation line to the data source bound by the GridView and manipulating its child controls after the GridView binds the data-are worth discussing.
Add demarcation lines to the data source of the binding GridView

When the GridView is bound to a data source, the GridView creates a gridviewrow from each record in the data source. So we can add a "demarcation record" before the data binding (binding), and Figure 3 describes the process.

Figure 3: Adding a demarcation line to the data source schematic diagram

The term "demarcation record" is quoted because it does not actually have this particular record, we just add some tag lines to the data source. For example, binding productsdatatable objects to gridview,productsdatatable is made up of productrow. We can mark a record as a "demarcation record" and set CategoryID to-1 (since-1 does not exist in the normal record).

Use this method to implement the following steps:
1. Get the data bound to Girdview (a Productsdatatable object)
2. SortExpression and SortDirection property arrangement data based on the GridView
3. Traverse the productsrows in the productsdatatable to find the dividing line of the sequence.
4. Insert "demarcation line" productsrow into the DataTable at the boundary of each group, CategoryID column value is-1 (or other value that can be labeled "Boundary Line").
5. Bind the data to the GridView dynamically after inserting the "demarcation line".

Complete the 5 steps above and, in the RowDataBound event, determine which rows are "boundary lines" (categoryid=-1 lines), and format the display style for the boundary line. There's a little more work to do, Preserves the values of Sortexpressiont and sortdirection in the sorting event.
After the GridView binds the data, add the additional TableRow object to the control set of the GridView

Before the GridView binds the data, it is better to add a "boundary line" after the GridView binds the data. The GridView is made up of a table, a table consists of rows set, and a row consists of a cells set, which is the control hierarchy of the GridView. The GridView root is a Table object, which is then generated by each record of the data source GridViewRow (derived from TableRow), the value of each cell of the data source is generated in the GridViewRow TableCell.
We can make use of the control hierarchy of the GridView to add a demarcation line between each group later. Because the control hierarchy of the GridView is created when the page is rendered, rewrite the Render method of the page class and add the demarcation line where needed, as Figure 4 describes the process.

Figure 4: Changing the GridView control hierarchy add boundary line schematic

This article will use the last method to create a custom sort user interface.

Note: The code used here is based on the playing a Bit with the GridView Sort grouping in the Teemu Keiski blog.

Step 3: Add the demarcation line to the control hierarchy of the GridView

If we want the control hierarchy of the GridView to be constructed and the line to be added before the page renders, it must be done in the last stage of the page lifecycle but before the GridView generates the HTML language, so rewrite the render method of the page class, such as the following code:

protected override void Render (HtmlTextWriter writer)
{
 //ADD code to manipulate the GridView control hierarchy
   base. Render (writer);
}

When the original render method of the page (base. Render (writer)) is invoked, each control of the page is displayed, and the resulting HTML markup is based on the control hierarchy. So we're bound to be in Base.render (writer) The control hierarchy that changes the GridView before being invoked. To add a boundary line you must ensure that the user is ordered, but at the beginning the GridView is not sorted by category and there is no need to add a demarcation line.

  Note: If you want the GridView to be sorted by default by a column, call the GridView Sort method in Page_Load, noting that you want to be in the IF (! IsPostBack). Please refer to pagination and sort data (paging and sorting) For more information about the sort method.

Assuming that the sort has been completed, the next step is to decide which column to sort and look for the boundaries of the different groups in the column, and the following code determines whether to sort and by which column to sort:

protected override void Render (HtmlTextWriter writer)
{
 //Only add the sorting UI if the GridView is sorted
 I F (!string. IsNullOrEmpty (productlist.sortexpression))
 {
  //determine the index and HeaderText of the column that 
  //the The data is sorted by
  int sortcolumnindex =-1;
  String sortcolumnheadertext = String. Empty;
  for (int i = 0; i < ProductList.Columns.Count i++)
  {
   if (productlist.columns[i). Sortexpression.compareto (productlist.sortexpression) = = 0)
   {
    sortcolumnindex = i;
    Sortcolumnheadertext = Productlist.columns[i]. HeaderText;
    break;
   }
  }

  Todo:scan the rows for differences in the sorted column ' s values
}

If the GridView is not sorted, SortExpression does not set a value. All we have to do is add a demarcation line to the already sorted gridview. After sorting is done, the next step is to sort by a few columns, traversing each column, Compare SortExpression to which column's HeaderText, and save the index and caption of the column with two variables sortcolumnindext and Sortcolumnheadertext respectively.

Know that after sorting by column, the last step is to add a demarcation line to the GridView, iterate through each row of the row, compare the value of each row with its current row, and then insert the dividing line in the middle, the code is as follows:

protected override void Render (HtmlTextWriter writer) {//Only add the sorting UI if the GridView is sorted if (!strin G.isnullorempty (productlist.sortexpression)) {//... The Code for finding the sorted column index removed for brevity ...//Reference the Table the GridView has been

  ed into Table gridtable = (table) productlist.controls[0]; Enumerate each TableRow, adding a sorting UI header if//the sorted value has changed string Lastvalue = String.
  Empty; foreach (GridViewRow gvr in productlist.rows) {string currentvalue = Gvr. Cells[sortcolumnindex].

   Text; if (Lastvalue.compareto (CurrentValue)!= 0) {//There ' s been a change in value in the sorted column int Rowind

    ex = GridTable.Rows.GetRowIndex (GVR); Add a new sort header row GridViewRow Sortrow = new GridViewRow (RowIndex, RowIndex, Datacontrolrowtype.datarow, Dat
    Acontrolrowstate.normal);
    TableCell Sortcell = new TableCell (); Sortcell.columnspan = productlist.coLumns.
    Count; Sortcell.text = string.
    Format ("{0}: {1}", Sortcolumnheadertext, CurrentValue);

    Sortcell.cssclass = "Sortheaderrowstyle";
    Add Sortcell to Sortrow, and Sortrow to Gridtable sortRow.Cells.Add (Sortcell);
    
    GridTable.Controls.AddAt (RowIndex, Sortrow);
   Update Lastvalue lastvalue = CurrentValue; {}} base.
Render (writer);

 }

First gets the root control of the GridView control hierarchy, a table, represented by gridtable. In addition, a string variable lastvalue represents the value of the previous line, CurrentValue represents the value of the current row.

  Note: I get the value assigned to Lastvalue and CurrentValue through the Text property of the cell (cells), which can only be applied to the binding column (BoundFields), for other kinds of columns such as template columns (TemplateField), check box columns ( CheckBoxField) and so on is not feasible, and I will explain later how to solve the problem of unbound column values.

Compare Lastvalue and CurrentValue, if different, add demarcation lines to the control hierarchy of the GridView. Gets the index of the current row, creating a GridViewRow object (which consists of TableCell) Inserted into the control hierarchy of the GridView. In addition, we want to format the demarcation line into a single cell, the same width as the GridView, the style and the applied Sortheaderrowstyle style (the CSS file is given below), and the text displayed is the sorted column name ( such as category) and group names (such as seafood), and finally assign CurrentValue to Lastvalue. The following is a CSS code:

. Sortheaderrowstyle
{
 background-color: #c00;
 Text-align:left;
 Font-weight:bold;
 Color:white;
}

After you complete the above code, you can sort the interface by binding columns (Figure 5 is the screenshot given after sorting by supplier). But I'm not yet able to generate a user-defined sort interface for other kinds of columns, such as Template columns or check box columns, as shown in Figure 6 ( Sort by discontinue).

Figure 5: Binding column Ordering

Figure 6: Sorting by Chectbox column does not appear demarcation line

Sorting by check box column The reason is that the code determines which column is sorted by obtaining the TableCell Text property, but the check box column TableCell text is empty. We're going to get the CheckBox control from the controls contained in TableCell. Encountered this type of column, to determine whether the checkbox is ticked, the CurrentValue = Gvr. Cells[sortcolumnindex]. Text is replaced with the following code:

String CurrentValue = String. Empty;
if (GVR. Cells[sortcolumnindex]. Controls.Count > 0)
{
 if (GVR). Cells[sortcolumnindex]. Controls[0] is CheckBox
 {
  if ((CheckBox) gvr. Cells[sortcolumnindex]. Controls[0]). Checked)
   CurrentValue = "Yes";
  else
   CurrentValue = "No";
 }

 // ... Add other checks-here-if using columns with the other
 //  Web controls in them (calendars, dropdownlists, etc.) ... 
   }
Else
 currentvalue = gvr. Cells[sortcolumnindex]. Text;

This code determines whether the control has a TableCell in the row, and if so, and the first control is a checkbox, assigns the CurrentValue to "Yes" or "NO" according to the Checked property of the checkbox. If the binding assigns the TableCell Text property value to CurrentValue. In the same way, template columns use this method. Figure 7 is a screenshot of the perfect code sorted by discontinue.

Figure 7: The demarcation line appears sorted by checkbox column

  Note: If the Categoryid,supplierid or UnitPrice in the database is null, then the GridView will appear as an empty string, which means that the demarcation line shows "Category:" and you can set the binding column's The NullDisplayText property displays the style more, or uses the CurrentValue to set the text that is displayed in the boundary line in the Render method.

Summarize

The GridView does not have a built-in custom sort interface, but we can create a custom sort interface by altering the control hierarchy of the GridView by some code, which explains how to add boundaries to the sortable GridView, allowing users to easily distinguish between different groups of boundaries. More examples of custom sort interfaces Please visit Scott Guthrie's blog a Few asp.net 2.0 GridView sorting Tips and tricks.

I wish you a happy programming!

Introduction of the author

Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, proficient in asp.net 2.0 within 24 hours. His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog http://scottonwriting.net/.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.