In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "the similarities and differences between GridView and DataGrid". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Similarities and differences between GridView and DataGrid
GridView is the successor control of DataGrid. Although DataGrid still exists in. Net framework 2, GridView has stepped on the foreground of history, and the trend of replacing DataGrid is irresistible. GridView and DataGrid function is similar, both display the data in the data source in 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 richer functions, because it provides a smart tag panel (that is, show smart tag) is more easy to use, commonly used sorting, paging, update, delete and other operations can be zero code to achieve! With the PagerTemplate attribute, you can customize the user navigation page, which means the control of paging is more arbitrary. There are also many differences between GridView and DataGrid in the event model. The DataGrid control raises a single event, while the GridView control raises two events, one before the operation and one after the operation, the pre-operation event is multi-bit * ing event, and the post-operation event is multi-bit * ed event, such as Sorting event and sorted event, RowDeleting and RowDeleted event.
Preliminary operation of GridView
1. Display the data in the data source
Select the GridView control from ToolBox and drag it to 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 in web.config, 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 condition, click Where, appear Add Where Clause, select the column for which you want to set the condition, whether the operator is equal to or like or something else, and then select Source, that is, where the qualified condition can be taken, such as Control, Session, Form, Cookie, QueryStirng, etc., if you select Control, you need to be on the right, select that control, and then you can also set the default value. After setting, the system automatically generates the Sql expression and the expression of the value. Click the Add button at this time to complete the addition of the condition. The condition just added appears under Where Cluase. If you don't click Add, it's easy to set the condition, but because it's not added to the Where clause, it doesn't work.
In this step, the Order By on the left allows us to set the sort order, that is, we can set three columns, ascending or descending, according to what kind of records we take out.
In this part, the Advanced on the left can be set to Advanced Sql Generation Options, where you can generate Insert, update, and Delete statements for this query, provided, of course, that the field you select contains the primary key. When you want to edit and delete tables without writing any code in GridView, you must generate Insert, Update, Delete statements here when configuring the data source. The zero code for editing and deleting operations in GridView completes the data source update and deletion operations according to these statements automatically generated when configuring the data source.
In the * * step, you can test whether the query you just generated is correct. Click finish, and the data is already on the page. Press Ctrl+F5 to run.
Congratulations! You already know how to use Asp.net to display the data in the database.
2. Let GridView be paginated
GridView shows the data, but it is not appropriate for so many records to be listed on one page. We should paginate the data. I still remember that in the era of asp, paging was so troublesome that it required a lot of code to be written, and a variety of paging components came into being. In GridView, you will find that paging is so simple, as long as you click the mouse, in Show Smart Tag, select Enable Paging, the paging operation of the table becomes complete, is it So Easy?
Not all data sources can allow GridView to achieve automatic paging, for example, if DataSourceMode is DataReader, automatic paging cannot be achieved. And only ObjectDataSource supports paging at the interface level, similar to our commonly used SqlDataSource, which first extracts all the records, then displays only the records that need to be displayed on this page, and then throws away the rest of the 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. Common properties include: PageIndex-- sets the current page of the data display, which defaults to 0, that 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 button for paging in detail. In the Mode property, you can set: Numeric-- default, paging is represented by numbers, 1, 2, and 3. NextPrevious, NextPreviousFirstLast, NumericFirstLast can all display the previous page, the next page, the home page, the last page, etc., as the name implies. When the Mode setting is not Numeric, then you can set FirstPageText, LastPageText and other properties to achieve paging navigation, to the first page, the last page, the next page, the text prompt displayed on the previous page.
If you want to achieve fully automatic control of the paging interface, you can also right-click GridView, select edit template-PagerTemplate to achieve, add a number of Button controls in the template, and 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 achieve paging operation.
3. Edit, delete and 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 and other operations on the data, or do not need to write any code, we can use the built-in functions of GridView to achieve.
In the smart tag, click the edit column, in Avaliable Fields, select ComandField, and then double-click Edit,update,cancel and Delete, and we add edit and delete capabilities to GridView. If we have generated Insert, update, delete statements when configuring the data source, we can execute the program now. Click Edit on the page, the Update and Cancel buttons appear, while the current row except the primary key column, the values are placed in a text box, you can edit, and then click Update to save. Click Delete to delete the current line record. Have you been impressed by the powerful features of GridView?
In Show Smart Tag, select Enable Sorting, and the Header of all columns becomes a hyperlink. In fact, these are all LinkButton controls. Run the code. In the data table generated by the web page, click on the column name in the * * row, and you can sort by the current column. Click again and sort in reverse.
If you only need to sort a few of these columns, you can select the edit column in the smart tag, select the column you want to sort, then find the SortExpression attribute in the properties on the right, and then select which field to sort by from the drop-down box, generally the current field, of course, to complete the sorting setting. If you don't need this column to participate in sorting, you just need to delete the value after the SortExpression attribute of this column, that is, set it to an empty string. Give it a try. Is the order under control?
Custom columns in GridView
GridView can automatically generate columns according to the data source, but if we need to customize the way the columns are displayed, so that the columns of GridView are completely controlled by ourselves, we need to use a special column-TemplateField. Because the columns generated by GridView are one field and one column, what if we need to merge the two fields into one column? We can use the template column. We can specify templates that contain tags and controls, customize the layout and behavior of columns, we can create a new template column, or we can personalize the generated columns directly into template columns.
Right-click on the GridView, select Edit template, select the column to be edited in the pop-up menu, and the editing screen of the column template appears. Among them, the content displayed in the header section of the HeaderTemplate-- custom column, which is displayed in the FooterTemplate-- footnote section? / SPAN > ItemTemplate-- is the content of this column data display after opening the web page, EditItemTemplate-- how to display this column when it is edited, and the content displayed by AlternatingItemTemplate-- alternating items, that is to say, for the display effect, it can be displayed in different styles in interlaced lines.
Example 1:
We now assume that there is a table where one field is username, and we now generate a custom column that contains the person's photo, and we assume that the path to the photo is image/username.jpg. We first right-click GridView, in the smart tag, select the 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 the Field Binding in ImageUrl. First, I want a column in the Bound to data source, because all the pictures have the same path and format, only the name is different, so we select the username field here. We need to define its format by ourselves. Enter image/ {0} .jpg. {0} represents the field bound above, and there is a check box below Two Way DataBinding, that is, whether it means two-way binding. If one-way binding is used, Eval is generally used, that is, values are only transmitted to the page from the data source. If two-way binding is used, that is, Bind is used, changes to the data can be transmitted back to the data source.
When the web page is executed, the names of the images will be replaced accordingly for different lines because of the different username. Click OK, and then execute the current 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 GridView automatically generates columns, CheckedBoxField columns are generally used to display bit type data, which is displayed on the web page as a checkbox. If selected, that is, Checked, it is male, otherwise it is female. This looks unintuitive, so let's display the gender as male and female by customizing the column.
First of all, in the Show Smart Tag of GridView, select the edit column, and then double-click TemplateFields to add a template column. When you are sure, right-click to select edit template, and select the column you just added. Add a DropListDown control to ItemTemplate, then edit its data binding, Edit DataBinding, and bind the SelectedValue attribute to the gender column.
Select Edit Item in the DropListDown control, which is the item that edits its drop-down list. We add two Item, one with a male Text property, a Value property set to True, a Text property set to female, and a Value property set to False. Come here, 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 Value of the Item whose Text attribute is male is True, so we are now running the web page. In the newly added column, we no longer display the single box or True, false and other meaningless things. Instead, the drop-down list shows whether the current user is male or female.
Data updates in custom columns
Suppose there is a permissions field in the database, with a value of 0 for unaudited users, 1 for general users, and 9 for administrator users. According to the custom column approach mentioned earlier, by binding to DropListDown, the permission is displayed in the web page as "administrator" instead of the number 9. The problem arises, if we adjust the user rights, such as changing the general user to an administrator, in editing the drop-down list of user rights in the template, how to return its value to the data source to complete the update operation.
The DropListDown control we set up in EditItemTemplate must have Two Way DataBinding selected, that is, two-way data help, in order to return data. As we mentioned earlier, in GridView, there are not a single event, but two events, one before and one after. Because we need to transmit the permission values of the drop-down list before the data update, we need to encode the GridView1_RowUpdating as follows:
Protected void GridView1_RowUpdating (object sender, GridViewUpdateEventArgs e) {/ / which line is currently edited? Int index = GridView1.EditIndex; / / get the GridViewRow object GridViewRow gvr = GridView1.Rows [index] of the current edit row; / / in the current row, look for the DropListDown control DropDownList dp = (DropDownList) gvr.FindControl ("editdrop"); / / assign the value of DropListDown to the permission field in the NewValues collection. E.NewValues ["rights"] = dp.SelectedValue;}
RowDataBound event
When creating a gridView control, you must first create a GridViewRow object for each row of GridView, and when you create each row, a RowCreated event will be raised; when the row is created, each row GridViewRow will bind the data in the data source, and when the binding is complete, the RowDataBound event will be raised. If we can use the RowCreated event to control the controls bound by each row, we can also use the RowDataBound event to control the data bound by each row, that is, how the data will be presented to you.
To give the same example, in the data table, there is a gender column. Above, we use the DataBounding of the DropListDown control to express the gender in Chinese, but it is not very beautiful after all. We can now use the Label control and the RowDataBound event to display the gender in Chinese. 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, and then double-click RowDataBound in the event list of the GridView control property to generate the following event:
Example:
Protected void GridView1_RowDataBound (object sender, GridViewRowEventArgs e) {/ / determine whether the current row is a data row if (e.Row.RowType = = DataControlRowType.DataRow) {/ / find the Label control Label lb1= (Label) e.Row.FindControl ("Label1") in the template using the FindControl method / / because RowDataBound occurs after data binding, we can / / judge the data bound by Label. If it is True, change its text attribute to male if (lb1.Text== "True") lb1.Text= "male"; else lb1.Text= "female";}}
RowType
RowType can determine the type of row in GridView, and RowType is a value in the rose variable DataControlRowType. RowType can include DataRow, Footer, Header, EmptyDataRow, Pager, and Separator. In many cases, we need to determine whether it is a data row or not, through the following code:
If (e.Row.RowType = = DataControlRowType.DataRow)
RowDeleting and RowDeleted events
RowDeleting occurs before data is deleted, and RowDeleted occurs after data is deleted.
Using the RowDeleting event, you can confirm whether to delete or cancel the deletion by setting GridViewDeleteEventArgs.Cancel=True, or it can be used to determine the number of records in the current database, prompt and cancel the delete operation if there is only one record left and the database cannot be empty.
Using the RowDeleted event, you can determine whether an exception occurred during deletion by the Exception property of GridViewDeletedEventArgs, and if there is no exception, you can display a prompt such as "1 Records deleted".
Example:
Protected void GridView1_RowDeleting (object sender, GridViewDeleteEventArgs e) {/ / gets the current line number and the GridViewRow object int index=e.RowIndex of the current line; GridViewRow gvr=GridView1.Rows [index]; / / gets the text str1 = gvr.Cells [1] .text in the second cell of the current line; / / prompts Message.Text = "you are about to delete a user whose name is" + str1 } protected void GridView1_RowDeleted (object sender, GridViewDeletedEventArgs e) {/ / if no exception is generated, prompt for successful deletion, otherwise prompt deletion failure if (e.Exception = = null) Message.Text + = "
< br>You successfully deleted "+ str1; else Message.Text + =" deletion failed, please contact the administrator;}
RowEditing event
The RowEditing event is raised before the row in GridView enters edit mode, which you can do here if you need to do some preprocessing before editing the record. If you want to cancel editing 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 line number of the current edit, and then get the gridviewrow object GridViewRow gvr = GridView1.Rows [e.NewEditIndex]; / / determine that if the name column of the current edit line is the admin user, cancel editing the if (gvr.Cells [1] .Text = "admin") e.Cancel = true;} of the current row
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 before the record is updated, such as changing the password, because the password is not stored in plaintext in the database and hash is carried out, so we should generate its hash value before updating the password, and then update the password. RowUpdated can verify that the update was successful.
Example:
Protected void GridView1_RowUpdating (object sender, GridViewUpdateEventArgs e) {GridViewRow gvr = GridView1.Rows [GridView1 .EditIndex]; / / find the control TextBox tb1 = (TextBox) gvr.FindControl ("tb_password") that enters the password; / / after storing the text hash in this control, store the password in the NewValues dictionary e.NewValues ["password"] = tb1.Text .GetHashCode (). ToString () } protected void GridView1_RowUpdated (object sender, GridViewUpdatedEventArgs e) {/ / if there is no exception, then if (e.Exception = = null) Message.Text + = "updated successfully!" ;}
Keys, OldValues, NewValues collections
The Keys dictionary generally stores the corresponding values of key and value of the primary key field in the data source. If the primary key consists of multiple fields, Keys adds its field name and value to each key field. What is stored in the OldValues is the field name and original value of the row to be updated, and each field is one of them. What is stored in the NewValues is the field name and modified value of the row to be updated, each of which is one of the items. Note that the primary key field is only stored in the keys collection.
Each of these three collections is an object of type DictionaryEntry. We can use DictionaryEntry.Key to determine the field name of an item and DictionaryEntry.Value to determine the value of an item.
In the above example, in order to encrypt the plaintext of 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) {/ / traverses NewValues and gets that each pair of DictionaryEntry objects foreach (DictionaryEntry de in e.NewValues) / / de.key is the field name. If you update a field separately here, you can also enter the field name directly, / / for example, e.NewValues ["password"] e.NewValues [de.Key] = Server.HtmlEncode (de.Value.ToString ());}
Example2:
Protected void GridView1_RowUpdating (object sender, GridViewUpdateEventArgs e) {/ / use Keys, OldValues, NewValues to get the primary key name, original data and updated data Message .Text = e.Keys ["username"] + "email address from" + e.OldValues ["email"] + "to" + e.NewValues ["email"];} "the similarities and differences between GridView and DataGrid" content is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.