Use of the gridview control in C #

Source: Internet
Author: User
Use of the gridview control in C #

1. Differences between the gridview and the DataGrid

The gridview is the successor control of the DataGrid. In framework 2, although the DataGrid still exists, the gridview has already taken to the foreground of history, and the trend to replace the DataGrid is unstoppable. Similar to the DataGrid function, the gridview displays data in the data source on the web page. A row of data in the data source, that is, a record, is displayed as a row in the output table on the web page.

Compared with the DataGrid, The gridview has the following advantages and features, because it provides a Smart Tag Panel (that is, show smarttag) for ease of use and convenience, common sorting, paging, update, and deletion operations can be implemented without code! With the pagertemplate attribute, you can customize the user navigation page, that is, the page control is more free. The gridview and DataGrid are also different in the event model. The DataGrid Control triggers a single event, while the gridview control triggers two events, one before the operation and the other after the operation, multiple ** ing events before the operation and multiple ** ed events after the operation, such as sorting events and sorted
Event, rowdeleting, and rowdeleted events.

 

Ii. Preliminary gridview operations

1. display data in the data source

Drag the gridview control from toolbox to the page, right-click, select Show Smart tag, and select new data source in choose datasource. Data Source configurationwizard appears, and select the connection string, you can choose to store it on the web. in config, you can select whether to use the stored procedure or select data from the table or view.

In this step, the where Statement on the Left can specify the query condition. Click where and add WHERE clause appears. Select the column to set the condition, and select whether the operator is equal to or like or other, and then select source, that is to say, the value of the condition to be specified can be control, session, form, Cookie, querystirng, etc. If control is selected, select the control on the right, you can also set the default value. After the setting is complete, the system automatically generates an SQL expression and a value expression. Then, click the Add button to add the condition. The newly added condition appears under wherecluase. If you do not click Add, it is easy to set conditions, but it does not work because it is not added to the WHERE clause.

In this step, the orderby on the left allows us to set the sorting columns, that is, what sort of records should we retrieve? Three columns can be set, in ascending or descending order.

In this section, advanced on the Left can be set to advanced SQL generationoptions. Here we can generate the insert, update, and delete statements for this query. Of course, the prerequisite is that the selected field must contain the primary key. If you want to edit or delete a table without writing any code in the gridview, insert, update, and delete statements must be generated here When configuring the data source. The zero code for editing and deleting operations in the gridview is to update and delete the data source based on the statements automatically generated when the data source is configured.

In the last step, you can test whether the query you just generated is correct, and click Finish. The data has already appeared on the page, and press Ctrl + F5 to run it.

Congratulations! You have used ASP to display data in the database.

 

2. Enable pagination for the gridview

The gridview displays the data, but it is not appropriate to list multiple records on one page. We should paging the data. I still remember how troublesome paging was in the ASP era. I had to write a lot of code and various paging components came into being. In the gridview, you will find that pagination is so simple, you just need to tap the mouse, In the showsmart tag, select enable paging, the paging operation of the table has been completed, is it so easy.

Not all data sources can enable automatic Paging for the gridview. For example, if the datasourcemode is datareader, automatic paging cannot be implemented. In addition, only objectdatasource supports pagination at the interface level. Similar to the commonly used sqldatasource, all records are extracted first, and only the records to be displayed on this page are displayed, and the remaining records are discarded, it's a waste of resources!

When the allowpaging attribute of the gridview is set to true, we implement pagination. We can also customize paging settings. Common attributes include pageindex, which is used to set the current page of data display. The default value is 0, which is the homepage of data. Pagesize-that is, the number of records displayed on a page. The default value is 10. In pagersettings, you can also set the paging navigation button in detail. In the mode attribute, you can set Numeric-default, which is represented by numbers on pages, 1, 2, 3 ....... Nextprevious, nextpreviusfirstlast, and numericfirstlast can be used as their names to display previous pages, next pages, home pages, and last pages. When mode is not set to numeric, you can set attributes such as firstpagetext and lastpagetext to display text prompts on the homepage, last page, next page, and top page.

If you want to implement full automatic control of the page interface, you can also right-click the gridview, select Edit template-pagertemplate, and add several button controls to the template, set the commandname attribute of the button control to page, and set the commandargument attribute to first, last, Prev, next, or a number to implement paging.

 

3. Editing, deleting, and sorting in the gridview

After the data is extracted from the data source and displayed on the webpage, you do not need to write any code to edit, update, or delete the data, use the built-in functions of the gridview.

In the intelligent tag, click Edit column. In avaliablefields, select comandfield and double-click Edit, update, cancel, and delete. The edit and delete functions are added to the gridview. If the insert, update, and delete statements have been generated when configuring the data source, we can execute the program now. Click Edit on the page, and the update and cancel buttons are displayed. Besides the primary key columns, the values of the current row are all placed in a text box. You can edit them and click Update to save the changes. Click Delete to delete the current row record. Have you been impressed by the powerful functions of the gridview?

In the show Smart Tag, select enablesorting. At this time, the headers of all columns are changed to a hyperlink. In fact, these are a linkbutton control and run the Code. In the data table generated on the webpage, click the column name in the first row to sort by the current column. Click again to sort the column in reverse order.

If you only need to sort several columns, you can select Edit columns in Intelligent tag, select the columns to be sorted, and find the sortexpression attribute in the attribute on the right, then, select the field to be sorted from the drop-down list, which is usually the current field. If you do not need this column to be sorted, you only need to delete the value after the sortexpression attribute of this column, that is, set it to an empty string. Have you tried sorting?

 

3. Custom columns in the gridview

The gridview can automatically generate columns based on the data source. However, if we need to customize the column display mode, we can completely control the columns in the gridview, we need to use a special column-templatefield. Because the columns generated by the gridview are all a field column, what if we need to combine the two fields into a column for display? We can use the template column. We can specify templates that contain tags and controls and customize the layout and behavior of columns. We can create a new template column, you can also directly convert generated columns into template columns for personalized settings.

Right-click the gridview, select Edit template, and select the column to be edited from the pop-up menu. The edit screen of the column template is displayed. Headertemplate-the content displayed in the header of the Custom column, and footertemplate-which of the following operations is displayed in the footer? /Span & gt; itemtemplate-indicates the content displayed in the data column after the webpage is opened. edititemtemplate-indicates how to display this column when it is being edited. alternatingitemtemplate-indicates the content displayed in alternate items, that is to say, in order to display the effect, you can display the results in different styles on different rows.

Example 1:

Assume that there is a table with a field username. Now we generate a Custom column that contains a photo of this person, at the same time, we assume that the photo path is image/username.jpg. Right-click the gridview, select the edit column in the Smart Tag, add a template column, edit the itemtemplate in the template, add an image control, right-click the image control, and select editdatabindings, set field binding in imageurl. First, I want a column in the bound to data source. Because the paths and formats of all images are the same, only the names are different, so here we select the username field. In the format, we need to define its own format. Input Image/02.16.jpg, {0} represents the field bound above, and there is a two
The check box of way databinding indicates whether to bind two-way data. If one-way binding is used, Eval is generally used. That is to say, the value is only transmitted from the data source to the page. If two-way binding is used, BIND is used, data modification can be uploaded back to the data source.

When executing a Web page, different rows have different usernames, and the image names are replaced accordingly. Click "OK" and then execute the current webpage. the user's photo is displayed in our custom column.

Example 2:

In databases, when storing gender data, BIT data is generally used, and the storage is true or false. When a column is automatically generated by the gridview, The checkedboxfield column is generally used to display BIT data, displayed on the webpage is a single token. if selected, it is checked, it is male, otherwise it is female. This looks unintuitive. Next we will display gender as male and female through custom columns.

In the show Smart tag of the gridview, select Edit column, double-click templatefields, add a template column, click OK, right-click Edit template, and select the newly added column. Add a droplistdown control to itemtemplate, edit its data binding, editdatabinding, and bind the selectedvalue attribute to the Gender column.

In the droplistdown control, select edititem to edit the items in the drop-down list. We add two items. One text attribute is male, the value parameter is set to true, and the other text attribute is set to female, set the value attribute to false. So far, do you understand? Because the displayed text and value of the dropdownlist control can be different, we use the data to bind the value of the Gender column, which is true or false and then reflected on the dropdownlist control, if the value is true, because the text attribute is true for the male item, we are running the webpage now, in the newly added column, it does not show anything that has no meaning, such as "single-digit", "true", or "false", but displays whether the current user is a male or female by pulling the list below.

 

4. Data Update in custom Columns

1. rowupdating event

Assume that the database has a "permission" field. If the value is 0, it indicates that the user is not audited. If the value is 1, it indicates that the user is normal. If the value is 9, it indicates the administrator user. According to the preceding method of customizing columns, by binding droplistdown, the permission is displayed as "Administrator" on the webpage instead of the number 9. The problem arises. If we adjust the user permissions, for example, change the general user to the Administrator. In the drop-down list of the user permissions in the editing template, how to return its value to the data source to complete the update operation.

The droplistdown control we set in edititemtemplate must have two waydatabinding selected, that is, two-way data help, in order to return data. As mentioned above, in the gridview, events are not single, but two. One is before and the other is after, because we need to transfer the permission value of the drop-down list before data update, We need to encode gridview1_rowupdating, the encoding is as follows:

Protected void gridview1_rowupdating (Object sender, gridviewupdateeventargs E)

{

// Which line is being edited?

      Int Index = gridview1.editindex;

// Obtain the gridviewrow object of the currently edited row

      Gridviewrow gvr = gridview1.rows [Index];

// Search for the droplistdown control in the current row

      Dropdownlist dp = (dropdownlist) gvr. findcontrol ("editdrop ");

// Assign the droplistdown value to the permission field in the newvalues set.

      E. newvalues ["rights"] = DP. selectedvalue;

}

 

2. rowdatabound event

When creating a gridview control, you must first create a gridviewrow object for each row of the gridview. When creating each row, A rowcreated event is triggered. When the row is created, each row of gridviewrow is bound to the data in the data source. When the binding is complete, the rowdatabound event is triggered. If we can use the rowcreated event to control the controls bound to each row, we can also use the rowdatabound event to control the data bound to each row, that is, how to present the data to everyone.

For example, there is a gender column in the data table. The databounding of the droplistdown control is used to indicate the gender in Chinese, but it is not very beautiful after all, now we can use the label control and rowdatabound event to achieve a perfect Chinese gender display. Rowdatabound,

First, set the Gender column as the template column, add a label control, and bind the label control to the gender segment of the data source, double-click rowdatabound In the event list of the gridview control property to generate the following event:

Example:

  Protected voidgridview1_rowdatabound (Object sender, gridviewroweventargs E)

{

// Determine whether the current row is a data row

      If (E. Row. rowtype = datacontrolrowtype. datarow)

      {// Use findcontrol to find the label control in the template

Label lB1 = (Label) E. Row. findcontrol ("label1 ");

// Because rowdatabound occurs after data binding, we can

// Determine the data bound to the label. If it is true, change its text attribute to male.

              If (lb1.text = "true ")

                    Lb1.text = "male ";

              Else

                    Lb1.text = "female ";

      }

  }

 

3. rowtype

Rowtype can be used to determine the type of the row in the gridview. rowtype is a value in datacontrolrowtype. Rowtype can be set to datarow, footer, header, emptydatarow, pager, and separator. Most of the time, we need to determine whether the current row is a data row and use the following code to determine whether the current row is a data row:

 If (E. Row. rowtype = datacontrolrowtype. datarow)

 

4. rowdeleting and rowdeleted events

Rowdeleting occurs before data is deleted, and rowdeleted occurs after data is deleted.

With the rowdeleting event, you can confirm whether to delete it again before deleting it. You can set gridviewdeleteeventargs. cancel = true to cancel the deletion. It can also be used to determine the number of records in the current database. If there is only one record left and the database cannot be blank, a prompt is displayed and the deletion operation is canceled.

With the rowdeleted event, you can use the gridviewdeletedeventargsThe exception attribute of to determine whether an exception is generated during the deletion process. If no exception exists, a prompt message similar to "1 records deleted" can be displayed.

Example:

  Protected voidgridview1_rowdeleting (Object sender, gridviewdeleteeventargs E)

{

// Obtain the current row number and obtain the gridviewrow object of the current row

      Int Index = E. rowindex;

      Gridviewrow gvr = gridview1.rows [Index];

// Obtain the text in the second cell of the current row

      Str1 = gvr. cells [1]. text;

// Prompt

      Message. Text= "You will delete a user whose name is" + str1;

  }

  Protected voidgridviewinclurowdeleted (Object sender, gridviewdeletedeventargsE)

{

// If no exception occurs, a message is displayed, indicating that the deletion is successful. Otherwise, a message is displayed, indicating that the deletion failed.

      If (E. Exception = NULL)

          Message. Text + = "& lt; BR & gt; you have deleted" + str1;

      Else

          Message. Text + = "deletion failed. Please contact the Administrator ";

}

 

5. rowediting event

The rowediting event is triggered before the row in the gridview enters the editing mode. If you need to perform some preprocessing before editing the record, you can perform operations here. To cancel editing the current row, set the cancel attribute of the gridviewediteventargs object to true.

Example:

  Protected voidgridviewinclurowediting (Object sender, gridviewediteventargs E)

{

// Use neweidindex to get the row number currently edited, and then obtain the gridviewrow object

      Gridviewrow gvr = gridview1.rows [E. neweditindex];

 

// Judge. If the name column of the current editing row is admin, the editing of the current row is canceled.

      If (gvr. cells [1]. Text = "admin ")

          E. Cancel = true;

}

 

6. rowupdating and rowupdated events

The rowupdating event occurs before the data source is updated, and the rowupdated event occurs after the data source is updated.

We can use rowupdating for preprocessing before record updates. For example, when changing a password, the password is hashed because it is not stored in plain text in the database. Therefore, before updating the password, the hash value should be generated before the update operation. Rowupdated checks whether the update is successful.

Example:

  Protected voidgridview1_rowupdating (Object sender, gridviewupdateeventargs E)

  {

      Gridviewrow gvr = gridview1.rows [gridview1.editindex];

// Find the control for entering the password

      Textbox tb1 = (textbox) gvr. findcontrol ("tb_password ");

// After the text in the control is hashed, the password is saved to the newvalues dictionary.

      E. newvalues ["password"] = tb1.text. gethashcode (). tostring ();

 

  }

  Protected voidgridview1_rowupdated (Object sender, gridviewupdatedeventargsE)

{

// If no exception occurs, the update is successful.

      If (E. Exception = NULL)

          Message. Text + = "updated successfully! ";

  }

 

7. Keys, oldvalues, and newvalues

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 is composed of multiple fields, keys adds the field names and values for 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 names and modified values of the rows to be updated. Each field is one of them. Note that primary key fields are only stored in the Keys set.

Each item in these three sets is a dictionaryentry type object. We can use dictionaryentry. Key to determine the field name of an item, and use dictionaryentry. Value to determine the value of an item.

In the preceding example, we used the newvalues field to reset the value of key to password in order to encrypt the plaintext of the password and store it in the database. To ensure security, we encode all values in newvalues in HTML before updating the data:

Example1:

Protected void gridview1_rowupdating (Object sender, gridviewupdateeventargs E)

{

// Traverse newvalues and obtain each pair of dictionaryentry objects

     Foreach (dictionaryentry de in e. newvalues)

 

// De. Key is the field name. If you update a field separately, you can enter the field name directly. // E. newvalues ["password"]

 

     E. newvalues [de. Key] = server. htmlencode (De. value. tostring ());

  }

Example2:

  Protected voidgridview1_rowupdating (Object sender, gridviewupdateeventargs E)

{

// Use keys, oldvalues, and newvalues to obtain the primary key name, original data, and updated data respectively.

      Message. Text= E. Keys ["username"] + "email address changed from" + E. oldvalues ["email"] + "to" + E. newvalues ["email"];

}

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.