Is the gridview control ASP. NET?
The successor of the 1. x DataGrid Control. It is a powerful universal control that can handle simple and common operations, such as paging, sorting, editing, or deleting data. Implement bidirectional data binding with as few data as possible. This control is closely integrated with the new data source control series. as long as the underlying data source object supports it, it can also directly process data source updates. It can define multiple primary key fields, new column types, style and template options.
Gridview supports a large number of attributes, including behaviors, visualization settings, styles, statuses, and templates.
Common behavior attributes of the gridview:
Allowpaging
Indicates whether the control supports paging;
Allowsorting indicates whether the control supports sorting;
Autogeneratecolumns
Indicates whether to automatically create columns for each field in the data source. The default value is true;
Autogeneratedeletebutton
Indicates whether the control contains a button column to allow users to delete records mapped to the clicked row;
Autogenerateeditbutton
Indicates whether the control contains a button column to allow users to edit records mapped to the row to be clicked;
Autogenerateselectbutton
Indicates whether the control contains a button column to allow users to select records mapped to the row to be clicked;
Deatamember
Indicates that a specific table in a multi-member data is bound to the grid. This attribute is used in combination with datasource. If datasource has a DataSet object, this attribute contains the name of the specific table to be bound;
Datasource
Obtain or set the data source object that contains the value used to fill the control;
Performanceid
Indicates the bound data source control;
EnableSortingAndPagingCallbacks
Indicates whether to use the script callback function to complete sorting and paging. Disabled by default;
RowHeaderColumn
Name of the Column Used as the column title. This attribute is designed to improve accessibility;
SortExpression to get the current sort expression;
UseAccessibleHeader
Specifies whether to generate a <th> label (instead of a <td> label) for the column title ).
Template attributes of the GridView control:
EmptyDataTemplate
Indicates the template content to be generated when the control is bound to an empty data source. If both this attribute and EmptyDataText are set, this attribute takes precedence. If neither attribute is set, the grid control is not generated when it is bound to an empty data source;
PagerTemplate
Indicates the template content to be generated for the page splitter. This attribute overwrites any settings we may make through the PagerSettings attribute.
The status attribute of the GridView control:
BottomPagerRow
Returns the GridViewRow object indicating the bottom part of the grid control;
Columns
Obtains a set of objects that represent columns in the grid. If these columns are automatically generated, the set is always empty;
DataKeyNames?
Obtains an array containing the names of the primary key fields currently displayed;
DataKey
Obtain the value of a primary key field that represents the currently displayed record in DataKeyNames;
EditIndex
Obtain and set a 0-based index to identify the row currently generated in edit mode;
Footerrow returns a gridviewrow object indicating the footer;
Headerrow returns a gridviewrow object that represents the title;
Pagecount
Obtain the number of pages required to display records of the data source;
Pageindex
Obtains or sets a 0-based index to identify the currently displayed data page;
Pagesize indicates the number of records to be displayed on a page;
Rows
Obtains a set of gridviewrow objects that indicate the currently displayed data rows in the control;
Selecteddatakey
Returns the datakey object of the selected record;
Selectedindex obtains and sets a 0-based index that identifies the currently selected row;
Selectedrow returns a gridviewrow object indicating the selected row;
Selectedvalue returns the explicit value of the key stored in the datakey object. Similar to selecteddatakey;
Toppagerrow returns a gridviewrow object that represents the top page splitter of the grid.
Gridview
Events triggered by controls:
Pageindexchanging,
Pageindexchanged
Both events occur when a page splitter button is clicked. They are triggered before and after the Grid Control handles paging operations;
Rowcancelingedit
The cancel button of a row in edit mode is clicked, but occurs before the row exits edit mode;
Rowcommand clicked a button;
Rowcreated
An error occurred while creating a row;
Rowdatabound occurs when a data row is bound to the data;
Rowdeleting, rowdeleted
Both events occur when the delete button of a row is clicked. They are triggered before and after the Grid Control deletes the row;
Rowediting
When the edit button of a row is clicked, it occurs before the control enters the editing mode;
Both rowupdating and rowupdated events occur when the update button of a row is clicked. They are triggered before and after the Grid Control updates the row;
Selectedindexchanging, selectedindexchanged
Both events occur when the select button of a row is clicked. They are triggered before and after the selection operation of the grid control;
Sorting, sorted
Both events occur when the hyperlink for sorting a column is clicked, which are triggered before and after the grid control processes the sorting operation.
Gridview binding
Configure columns: The following Code adds a data-bound column to the grid:
<Asp: gridview id = "gridview1"
Runat = "server" performanceid = "sqlperformance1">
<Columns>
<Asp: BoundField DataField = "companyname"
HeaderText = "Product Name"/>
</Columns>
<EmptyDataTemplate>
</EmptyDataTemplate>
</Asp: GridView>
Bind columns in the GridView. These column field classes inherit DataControlField:
BoundField
The default column type. Displays the value of a field as plain text;
ButtonField is used as a command to display the value of a field. We can select the link button or button switch style;
CheckBoxField is used as a check box to display the value of a field. It is usually used to generate a Boolean value;
CommandField
It is an enhanced version of ButtonField, indicating a special command, such as Select, Delete, Insert, or Update. This attribute is almost useless to the GridView control. This field is customized for the DetailsView control;
HyperLinkField is used as a hyperlink to display the value of a field. Click the hyperlink and navigate to the specified URL;
ImageField
As the Src attribute of the HTML Tag, the value of a field is displayed. The content of the bound field should be the URL of the physical image;
TemplateField
Displays user-defined content for each item in the column.
The public attribute of the GridView column represents a subset of the attribute actually provided by each column type;
AccessibleHeaderText
Indicates the same ive
Text of the abbreviated text read by the screen reader of the Technology device;
FooterStyle gets the style object of the footer of the column;
FooterText gets and sets the text of the footer of the column;
HeaderImageUrl: Obtain and set the URL of the image in the title of the column;
HeaderStyle: gets the style object of the column title;
HeaderText: Obtain and set the text of the column title;
InsertVisible indicates whether the field is visible when its parent data binding control is in insert mode;
ItemStyle gets the style object of the units in each column;
ShowHeader indicates whether to generate the column title;
SortExpression: the expression used to sort the grid when the column title is clicked;
Bind Fields
The BoundField class indicates a data binding control (such as the GridView
Or DetailsView. To specify the fields to be displayed, set the DataField attribute to the field name. to display a title in the header or footer, set the HeaderText and FooterText attributes respectively;
Button Field
The button field indicates any operation that we want to process through a server event. When this button is clicked, the page returns and generates a RowCommand event.
Hyperlink Field
The hyperlink column directs users to a different URL, which can be selectively displayed in an internal framework.
For example:
<Asp: HyperLinkField
ID = "HyperLinkField1" runat = "server"
DataNavigateUrlFields = "id"
DataNavigateUrlFormatString = "Flower. aspx? Id = {0 }"
DataTextField = "name" HeaderText = "flowers"
/>
When you click this button, the browser uses Flower. aspx? Id = XXX
CheckBox Field
The checkboxfield column is a simple binding column for displaying a check box.
Image Field
The imagefield column type indicates a field displayed as an image in the data binding control.
Template Field
Sometimes we need to bind fields in special formats, which are customized columns. You can obtain the result by using the template.
The templatefield column provides a personalized user interface for each row in the grid, which is completely defined by PAGE developers. we can generate a stage definition template in the name, includes default view, in-situ editing, title, and footer.
Template supported by the gridview Control
Alternatingitemtemplate defines the content and appearance of the alternating line. If no template is specified, itemtemplate is used;
Edititemtemplate defines the content and appearance of the row being edited. This template contains input fields and may also contain verification programs;
Footertemplate defines the content and appearance of the footer of the row;
Headertemplate defines the content and appearance of the line title;
Itemtemplate defines the default content and appearance of the row.
A templated view can contain something that makes sense to the application we are creating: server controls, text and data binding expressions.
The data binding expression allows us to insert values contained in the current data row. However, not all templates support data binding expressions.
The following code defines a project template for a product. This column is currently displayed, and includes the product name and some information about product packaging.
<Asp: templatefield>
<ItemTemplate>
<% # Eval ("productName ")
%> <Br/>
Available in <% #
Eval ("quantityperunit") %>
</ItemTemplate>
</Asp: TemplateField>
Data Binding syntax
ASP. NET has the following two data binding syntaxes:
1. Use the Eval Method
It can calculate the data expression bound to the template of the data binding control. The Eval method uses the data field name as the parameter.
The Eval method can bind data expressions in the templates of various data binding controls. At runtime, the Eval method calls the Eval method of the DataBinder object and references the current data item of the named container. A naming container is usually the smallest component of a data binding control that contains a complete record, such as a row in the GridView control.
The Eval method uses the name of a data field as a parameter and returns a string containing the value of this field from the current record of the data source. String Format parameters are defined using the Format method of the String class.
Eval is a read-only methodology (Oriented Data Binding). The bound content is not submitted back to the server. For example, if you do not want the user to make any changes, you can use:
<% #
Eval ("UserName"). ToString. Trim ()
%>
Eval also has an overloaded Method for formatting. For example, you can use:
<% #
Eval ("RegTime", "{0: dd/MM/yyyy }")
%>
0 indicates the PublishDate field, while dd/MM/yyyy indicates the format of the final displayed text, which may be displayed as 17/07/2009.
2. Use the Bind method
The Bind method has some similarities with the Eval method, but there are also great differences. Although the Bind method can be used to retrieve the value of a Data Binding field like the Eval method, the Bind method must be used when the data can be modified to a local location.
The Bind method is usually used with the input control, for example, the TextBox Control rendered by the row of the GridView in editing mode. When the data binding control creates these input controls as a part of its own rendering, this method can extract the input value.
The Bind method supports read/write functions (two-way data binding). This method is often used with input controls (such as TextBox controls) to update data. You can modify the title of a book:
<% #
Bind ("Title") %>
GridView in-depth
1. Highlight
When we move the cursor to a row in the GridView, the line is highlighted. The Code is as follows:
Protected void
Gridviewdomainrowdatabound (object sender, GridViewRowEventArgs e)
// Determine whether the table is a data row, that is, the table header and the end.
{
If (e. Row. RowType =
DataControlRowType. DataRow)
{
E. Row. Attributes. Add ("onmouseover ",
"Currentcolor = this. style. backgroundColor; this. style. backgroundColor = 'yellow', this. style. fontWeight = 'bold '");
E. Row. Attributes. Add ("onmouseout ",
"This. style. backgroundColor = currentcolor, this. style. fontWeight = ''");
}
}
If you want to highlight a cell instead of a whole row, you can also use this method. For example, to highlight a cell whose price is "199.00", the code is:
If
(Flower. Models. Product) e. Row. DataItem). Price. Trim () = "199.00 ")
{
E. Row. Cells [3]. BackColor =
System. Drawing. Color. Yellow;
}
2. Deletion prompt
When we perform the delete operation, we need a prompt to delete the operation only after the user confirms it. In this case, we generally use the template column for processing. The Code is as follows:
<Asp: TemplateField>
<ItemTemplate>
<Asp: LinkButton ID = "LinkButton1" runat = "server"
OnClientClick = "javascript: return confirm ('the record cannot be recovered once deleted. Are you sure you want to delete it? ')"
CausesValidation = "false" CommandName = "Delete"
Text = "delete"> </asp: LinkButton>
</ItemTemplate>
</Asp: TemplateField>
3. Select the full result of the check box in the GridView
Sometimes, we need to delete multiple records. To make it easier for users, we do not want to delete each record once, but want a check box to delete multiple records at a time, instead of deleting and confirming again and again. At this time, you can use the check box to achieve the effect of multiple selections.
First, create a template column, place the CheckBox control in it, and write the client script. The Code is as follows:
<Script
Language = "javascript">
Function
GetAllCheckBox (CheckAll)
{
Var items =
Document. getElementsByTagName ("input ");
For (var I = 0; I <
Items. length; I ++)
{
If (items [I]. type =
"Checkbox ")
{
Items [I]. Checked =
Checkall. checked;
}
}
}
</SCRIPT>
In addition, you need to add the onclick = "getallcheckbox (this)" event on the check box before "Select All". The gridview code is as follows:
<Asp: templatefield>
<HeaderTemplate>
<Input id = "cbAll" type = "checkbox" onclick = "GetAllCheckBox (this )"
/> Select all
</HeaderTemplate>
<ItemTemplate>
<Asp: CheckBox ID = "CheckBox1"
Runat = "server"/>
</Itemtemplate>
</ASP: templatefield>
4. Fixed the header
Fixed Header: in the case of a drop-down table, the header moves down, so that the header is in a fixed position relative to the user and the browser, allowing the user to see the corresponding content of the field at any time. The code for creating a floating style is as follows:
<Style
Type = "text/CSS">
. Freezing
{
Position: relative;
Table-layout: fixed;
Top: expression (this. offsetparent. scrolltop );
Z-index: 10;
}
. Freezing th
{
Text-overflow: ellipsis;
Overflow: hidden;
White-space: nowrap;
Padding: 2px;
}
</Style>
Set the cssclass value of headersytle in the gridview to freezing.
5. Hide a column
Sometimes, too many columns in the result is also an annoyance. To meet the needs of different users, you may need to set whether to display certain rows.
To hide the ID, write the following code:
<Asp: checkbox
Id = "CBID" runat = "server" autopostback = "true" text = "Hide ID"
Oncheckedchanged = "cbID_CheckedChanged"/>
The Event code is:
Protected void
CbID_CheckedChanged (object sender, EventArgs e)
{
GridView1.Columns [2]. Visible =! GridView1.Columns [2]. Visible;
Response. Write ("the current hidden state of the ID column is:" + GridView1.Columns [2]. Visible. ToString ());
}