Similarities and similarities between GridView and DataGrid
GridView is the successor to DataGrid. In .net framework 2, although DataGrid still exists, GridView has entered the forefront of history, and the trend of replacing DataGrid is unstoppable. GridView and DataGrid functions are similar. Both display data in the data source on the web page, and display a row of data in the data source, that is, a record, as a row in the output table on the web page.
Compared with DataGrid, GridView has the following advantages and is more diverse in functions, because it provides a smart tag panel (that is, show smart tag) which is easier to use and convenient. Commonly used sorting, paging, update, deletion and other operations can be implemented in zero code! It has the PagerTemplate property, which allows you to customize the user navigation page, which means that the pagination control is more at will. GridView and DataGrid have many differences in event models. The DataGrid control triggers a single event, while the GridView control will cause two events, one occurs before the operation and the other occurs after the operation. The event before the operation is multi-bit ***ing event, and multiple-bit ***ed events after the operation, such as the Sorting event and sorted event, RowDeleting and RowDeleted events.
Preliminary GridView operation
1. Display data in the data source
Select the GridView control from ToolBox and drag it onto the page, then right-click, select Show Smart Tag, select New Data Source in Choose Data Source, Data Source Configuration Wizard appears, select the connection string, you can select the ConnectionString that has been stored, and then you can choose whether to use stored procedures, or select data from tables or views.
In this step, the Where statement on the left can specify the query conditions. Click Where, Add Where Clause appears, select the column to set the condition, whether the operator is equal or like or other, and then select Source, that is, where to get the value of the condition to be limited, which can be Control, Session, Form, Cookie, QueryStirng, etc. If Control is selected, you need to be on the right, select which control is, and then you can also set the default value. After setting, the system will automatically generate the expression of Sql expression and value. At this time, click the Add button to complete the addition of the conditions. The condition you just added appears under Where Cluase. If Add is not clicked, it is easy to set the conditions, but it does not work because it is not added to the Where clause.
In this step, the Order By on the left allows us to set the sorting sequence, which is what sort of python we take the records to follow. You can set three columns, whether they are ascending or descending.
In this part, Advanced on the left, you can set Advanced Sql Generation Options, where the Insert, update, and Delete statements for this query can be generated. Of course, the premise is that the field you select must contain the primary key. When you want to do not write any code in the GridView to implement editing, deleting, etc., you must generate the Insert, Update, and Delete statements here when configuring the data source. The zero code for editing and deletion operations in GridView is to complete the update and deletion operations of the data source based on these statements automatically generated when configuring the data source.
In the last step, you can test whether the query you just generated is correct. Finally, click Finish. The data has appeared on the page. Press Ctrl+F5 to run.
Congratulations! You will already use it to display the data in the database.
2. Make GridView pagination
GridView displays the data, but it is inappropriate to list so many records on one page. We should paginate the data. I still remember how troublesome pagination was in the Asp era, it required a lot of code to write, and various pagination components also came into being. In GridView, you will find that paging is so simple. You just need to click the mouse and select Enable Paging in the Show Smart Tag. The paging operation of the table has been completed. Is it So Easy?
Not all data sources can enable GridView to automatically paging. For example, if DataSourceMode is a DataReader, automatic paging cannot be implemented. Moreover, only ObjectDataSource is an interface-level pagination support. Similar to the SqlDataSource we commonly use, we first extract all records, then only display the records that need to be displayed on this page, and then discard the other records, which is a bit of a waste of resources!
When the AllowPaging property of GridView is set to True, we implement paging, and we can also make some personalized settings for paging. Commonly used attributes include: PageIndex - Set the current page of data display, the default is 0, which is the home page of the data. PageSize - that is, how many records are displayed on a page, the default is 10. In PagerSettings, you can also set the navigation buttons of the page in detail. In the Mode property, you can set: Numeric - default, the page is represented by numbers, 1, 2, 3... NextPrevious, NextPreviousFirstLast, NumericFirstLast can all display the previous page, next page, home page, last page, etc. as the name suggests. When the Mode setting is not Numeric, you can set properties such as FirstPageText and LastPageText to realize the text prompts displayed when you go to the homepage, last page, next page, and previous page.
If you want to implement full automatic control of the pagination interface, you can also right-click GridView and select Edit template - PagerTemplate to implement it. Add several Button controls to the template, then set the CommandName property of the Button control to Page, and set the CommandArgument property to First, Last, Prev, Next or a number respectively to realize the pagination operation.
3. Edit, delete, sort in GridView
After the data is extracted from the data source and displayed on the web page, if we need to edit, update, delete the data in it, we still don’t need to write any code, and use the built-in functions of GridView.
In the smart tag, click the Edit column, in Avalable Fields, select CommandField, and then double-click Edit, update, cancel and Delete, and we add edit and delete functions for GridView. If we have generated Insert, update, and delete statements when configuring the data source, then we can execute the program now. Click Edit on the page and the Update and Cancel buttons appear. At the same time, the columns except the primary key of the current row are placed in a text box. You can edit it, and then click Update to save it. Click Delete to delete the current row record. Have you been impressed by the powerful features of GridView?
In the Show Smart Tag, select Enable Sorting, and the headers of all columns become a hyperlink. In fact, these are all LinkButton controls. Run the code and in the data table generated by the web page, click the column name in the first row to sort according to the current column. Click again to sort it in reverse.
If you only need to sort a few of the columns, you can select the edit column in the smart tag, select the column to be sorted, and then find the SortExpression property in the properties on the right, and then select which field to sort from the drop-down box. Generally, it is of course the current field, and complete the sorting setting. If you do not need this column to participate in the sorting, you only need to delete the value after the SortExpression property of this column, that is, set it to an empty string. Let’s try it, is the sorting already in your grasp?
Custom columns in GridView
GridView can automatically generate columns based on the data source, but if we need to customize the display method of the columns and let the columns of the GridView be completely controlled by ourselves, we need to use a special column - TemplateField. Because the columns generated by GridView are all one field and one column, what if we need to merge two fields into one column to display? We can use template columns. We can specify templates containing tags and controls, customize the layout and behavior of the columns. We can create a new template column, or directly convert the generated columns into template columns for personalized settings.
Right-click on GridView, select Edit Template, and select the column to be edited in the pop-up menu. The column template editing screen appears. Among them, HeaderTemplate - the content displayed in the header part of the custom column, FooterTemplate - which footnote part is displayed? /SPAN>ItemTemplate - is the content displayed in this column after opening the web page, EditItemTemplate - how to display this column when it is in the edit state, Alternating ItemTemplate - the content displayed in alternating items, that is, for the purpose of displaying the effect, it can be displayed in different styles separately.
Example 1:
Let's now assume that there is a table with a field that is username, we now produce a custom column that contains the photo of this person, and we assume that the path of the photo is image/. We first right-click the GridView, in the smart tag, select Edit column, add a template column, then edit the ItemTemplate in the template, add an Image control, then right-click the Image control, select Edit DataBindings, and set Field Binding in ImageUrl. First of all, I want to Bound to a column in the data source, because the path and format of all images are the same, only the names are different, so we select the username field here. In format, we need to define its format by ourselves, enter image/{0}.jpg, {0} represents the field bound above, and there is a Two Way DataBinding below The check box of , means whether to bind in two directions. If it is bound in one direction, Eval is generally used, that is, the value is only transmitted from the data source to the page. If it is bound in two directions, that is, Bind is used, modifications to the data can be transmitted back to the data source.
When executing a web page, different lines will be replaced accordingly due to different usernames. Click OK, and then execute the current web page, and we can see that the user's photo is displayed in our custom column.
Example 2:
In the database, when storing gender, the bit data type is generally used, which is stored as True or False. When the GridView automatically generates a column, the CheckedBoxField column is generally used to display bit-type data. It is a radio box displayed on the web page. If selected, it is Checked, it is a man, otherwise it is a woman. This looks very unintuitive. Below we display the gender as male and female through custom columns.
First, in the Show Smart Tag of GridView, select the Edit Column, and then double-click TemplateFields to add a template column. After confirming, right-click to select the Edit Template and select the column you just added. Add a DropListDown control in ItemTemplate, then edit its data binding, Edit DataBinding, and bind the SelectedValue property to the gender column.
Select Edit Item in the DropListDown control to edit the item in its drop-down list. We add two Items, one of which is a male, the Value is set to True, the other whose Text property is set to Female, and the Value property is set to False. At this point, do you understand? Because the display text of the DropDownList control can be different from its value, we use data binding to get the value of the gender column, True or False, and then reflect it on the DropDownList control. If the value is True, because the Text property is the Value of the Male Item is True, so we are running the web page now. In the newly added column, the display is no longer a radio box or True or False that has no meaning, but the following list shows whether the current user is a man or a woman.
Data updates in custom columns
Suppose there is a "Permission" field in the database, with a value of 0 that represents unaudited users, 1 that represents general users, and 9 that represents administrator users. According to the custom column method mentioned above, by binding DropListDown, the permission is "administrator" in the web page, instead of the number 9. The problem arises. If we adjust user permissions, such as changing the general user to an administrator, editing the drop-down list of user permissions in the template, how to return its value to the data source to complete the update operation.
The DropListDown control we set in EditItemTemplate must select Two Way DataBinding, which means the data is determined in both directions, so that the data can be returned. As we mentioned earlier, in GridView, events are not single, but two, one is before and the other is after. Because we need to transmit the permission value of the drop-down list before data is updated, we need to encode GridView1_RowUpdating, and the encoding is as follows:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//What line is currently editing?
int index = ; //Get the GridViewRow object of the current editing line
GridViewRow gvr = [index]; //In the current row, look for the DropListDown control
DropDownList dp = (DropDownList)("editdrop"); // Assign the value of DropListDown to the permission field in the NewValues collection.
["rights"] = ;
}
RowDataBound Event
When creating gridView control, you must first create a GridViewRow object for each row of the GridView. When each row is created, a RowCreated event will be raised; when the row is created, each row of GridViewRow will bind the data in the data source. When the binding is completed, a RowDataBound event will be raised. If we can use the RowCreated event to control the controls bound to each row, then we can also use the RowDataBound event to control the data bound to each row, that is, how the data is presented to everyone.
Let’s give the same example. In the data table, there is a gender column. Above we use the DataBounding of the DropListDown control to represent the gender of Chinese, but it is not very beautiful after all. We can now use the Label control and RowDataBound event to achieve a perfect Chinese gender display. RowDataBound,
First, set the gender column as the template column, and add a Label control to bind the Label control to the gender segment of the data source. Then, we double-click RowDataBound in the event list of the GridView control properties to generate the following event:
Example:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Judge whether the current row is a data row
if ( == )
{
//Use the FindControl method to find the Label control in the template.
Label lb1= (Label)("Label1");
//Because RowDataBound occurs after data binding, we can
//Judge the data bound to Label. If it is True, change its text attribute to male.
if (== "True")
= "Male";
else
= "female";
}
}
RowType
RowType can determine the type of row in GridView, and RowType is a value in the Rose variable DataControlRowType. RowType can be used to include DataRow, Footer, Header, EmptyDataRow, Pager, and Separator. Many times, we need to determine whether it is currently a data line and make a judgment through the following code:
if ( == ) RowDeleting and RowDeleted events
RowDeleting occurs before deleting data, and RowDeleting occurs after deleting data.
Using the RowDeleting event, you can confirm whether to delete again before the actual deletion is actually deleted. You can cancel the deletion by setting =True; it can also be used to judge the current number of records in the database. If there is only one record left and the database cannot be empty, prompt and cancel the deletion operation.
Using the RowDeleted event, you can determine whether an exception occurred during the deletion process by using the Exception property of GridViewDeletedEventArgs after deletion. If there is no exception, prompt information similar to "1 Records deleted" can be displayed.
Example:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Get the current line number and get the GridViewRow object of the current line
int index= ;
GridViewRow gvr=[index]; //Get the text in the second cell of the current row
str1 = [1].Text; //Tip
="You will delete a user with the name "+str1 ;
}
protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
//If no exception occurs, the prompt will be prompted to be successfully deleted, otherwise the prompt will be prompted to be failed to delete.
if ( == null)
+= "< br>You have successfully deleted"+str1 ;
else
+= "Deletion failed, please contact the administrator";
}
RowEditing Event
RowEditing event is raised before the rows in the GridView enter edit mode, which can be done here if you need to do some preprocessing before editing the record. If you want to cancel the editing of the current line, you can set the Cancel property of the GridViewEditEventArgs object to true.
Example:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//Use NewEidIndex to get the currently edited line number, and then get the gridviewrow object
GridViewRow gvr = [];
//Judge, if the name column of the current editing line is the admin user, the editing of the current line will be cancelled.
if ([1].Text =="admin")
= true;
}
RowUpdating and RowUpdated events
The RowUpdating event occurs before the data source is updated, and RowUpdated occurs after the data source is updated.
We can use RowUpdating to do some preprocessing work before recording updates. For example, when modifying passwords, because the password is not stored in plaintext in the database and hash is performed, so before updating the password, it should generate its hash value and then update it. RowUpdated can verify that the update is successful.
Example:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow gvr = [GridView1 .EditIndex ]; //Looking for the control to enter the password
TextBox tb1 = (TextBox)("tb_password"); //After hash the text in this control, save password into the dictionary NewValues
["password"] = .GetHashCode().ToString () ;
}
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
//If there is no exception, the update will be successful
if ( == null)
+= "Updated successfully!";
}
Keys, OldValues, NewValues collection
The keys dictionary generally stores the corresponding values of the key and value of the primary key field in the data source. If the primary key consists of multiple fields, then Keys adds its field name and value to each key field. OldValues stores the field name and original value of the row to be updated, each field is one of them. NewValues stores the field name and modified value of the row to be updated, each field is one of them. Note that the primary key field is only stored in the keys collection.
Each item in these three sets is an object of type DictionaryEntry, which we can use to determine the field name of an item and to determine the value of an item.
In the above example, in order to encrypt the password and then store it in the database, we used the NewValues field to reset the value of the item whose key is password. To ensure security, we html encode all values in NewValues before updating the data:
Example1:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Transf the NewValues and obtain each pair of DictionaryEntry objects.
foreach (DictionaryEntry de in )
//It is the field name. If a certain field is updated separately here, you can also fill in the field name directly.
//For example ["password"]
[] = (());
}
Example2:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Use Keys, OldValues and NewValues to obtain the primary key name, original data and updated data respectively.
Message .Text = ["username"] + "The email address of " is changed from " + ["email"] + " to " + ["email"];
}
This is the introduction to the knowledge about GridView control operation.