Data operation skills in the gridview in ASP. net2.0

Source: Internet
Author: User
1. Export the content in the gridview to excel

In daily work, the content in the gridview is often exported to an Excel report. In Asp.net 2.0, you can also easily export the content in the entire gridview to an Excel report. The following describes the specific practices:

First, create the basic page default. aspx

<Form ID = "form1" runat = "server">
<Div>
<Asp: gridview id = "gridview1" runat = "server">
</ASP: gridview>
</Div>
<Br/>
<Asp: button id = "btnexport" runat = "server" onclick = "btnexport_click"
TEXT = "export to excel"/>
</Form>

In default. aspx. CS, write the following code:

Protected void page_load (Object sender, eventargs E)
{
If (! Page. ispostback)
{
Binddata ();
}
}
Private void binddata ()
{
String query = "select * from MERs ";
Sqlconnection myconnection = new sqlconnection (connectionstring );
Sqldataadapter ad = new sqldataadapter (query, myconnection );
Dataset DS = new dataset ();
Ad. Fill (DS, "MERs ");
Gridview1.datasource = Ds;
Gridview1.databind ();
}

Public override void verifyrenderinginserverform (Control)
{
// Confirms that an htmlform control is rendered
}

Protected void button#click (Object sender, eventargs E)
{
Response. Clear ();
Response. addheader ("content-disposition", "attachment?filename=filename.xls ");
Response. charset = "gb2312 ";
Response. contenttype = "application/vnd.xls ";
System. Io. stringwriter stringwrite = new system. Io. stringwriter ();
System. Web. UI. htmltextwriter htmlwrite = new htmltextwriter (stringwrite );

Gridview1.allowpaging = false;
Binddata ();
Gridview1.rendercontrol (htmlwrite );

Response. Write (stringwrite. tostring ());
Response. End ();
Gridview1.allowpaging = true;
Binddata ();
}
Protected void paging (Object sender, gridviewpageeventargs E)
{
Gridview1.pageindex = E. newpageindex;
Binddata ();
}

In the above Code, we first bind the gridview to the specified data source, and then write the relevant code in the button1 button (used for exporting to excel) event. Use the filenamein response. addheader ("content-disposition", "attachment?filename=exporttoexcel.xls" to specify the file name of the file to be imported. This is exporttoexcel.xls. Note that the content of the gridview may be displayed by page. Therefore, when exporting an Excel file, set the allowpaging attribute of the gridview to false, then, export the current page's gridview to excel using the page stream, and then reset its allowpaging attribute. In addition, you need to write an empty verifyrenderinginserverform method (which must be written) to confirm that the htmlform control is displayed for the specified ASP. NET Server Control at runtime.

  2. access various controls in the gridview

In the gridview, you often need to access various controls, such as dropdownlist, radiobutton, and checkbox. The following describes how to access various controls in the gridview.

First, let's see how to access the dropdownlist control in the gridview. Assume that in a gridviw, You need to select the content in the dropdownlist control from the drop-down menu for each record displayed, you can use the following code, after you select the dropdownlist control option in the gridview and click the button, the system prints the dropdownlist controls selected by the user and outputs their values.

Public dataset populatedropdownlist ()
{
Sqlconnection myconnection = new sqlconnection (configurationmanager. connectionstrings ["mydatabase"]. connectionstring );
Sqldataadapter ad = new sqldataadapter ("select * From tblphone", myconnection );
Dataset DS = new dataset ();
Ad. Fill (DS, "tblphone ");
Return Ds;
}

The above code first returns the data of the tblphone table in the database in the form of dataset. Then, in the itemtemplate of the page, the design is as follows:

<Itemtemplate>
<Asp: dropdownlist id = "dropdownlist1" runat = "server" datasource = "<% # populatedropdownlist () %>"
Datatextfield = "phone" datavaluefield = "phoneid">
</ASP: dropdownlist>
</Itemtemplate>

Note that the datasource attribute of the dropdownlist control is bound to the dataset (the populatedropdownlist () method is called) returned. You must set the extextfield and datavaluefield attributes.

Then, write the following code in the button event:

Protected void button2_click (Object sender, eventargs E)
{
Stringbuilder STR = new stringbuilder ();
Foreach (gridviewrow gvr in gridview1.rows)
{
String selectedtext = (dropdownlist) gvr. findcontrol ("dropdownlist1"). selecteditem. text;
Str. append (selectedtext );
}
Response. Write (Str. tostring ());
}

Here, we use a loop to obtain the value of the dropdownlist Control for each row, and add the value to the string for final output.

Next, let's see how to access the checkbox control in the gridview control. In the gridview control, you need to select multiple functions. In this case, you need to use the checkbox control. First, create a template column with the following checkbox:

<Asp: gridview id = "gridview1" runat = "server" allowpaging = "true" allowsorting = "true"
Autogeneratecolumns = "false" datakeynames = "personid" performanceid = "mysource" width = "366px" cellpadding = "4" forecolor = "#333333" gridlines = "NONE">
<Columns>
<Asp: commandfield showselectbutton = "true"/>
<Asp: boundfield datafield = "personid" headertext = "personid" insertvisible = "false"
Readonly = "true" sortexpression = "personid"/>
<Asp: boundfield datafield = "name" headertext = "name" sortexpression = "name"/>
<Asp: templatefield headertext = "select">
<Itemtemplate>
<Asp: checkbox id = "chkselect" runat = "server"/>
</Itemtemplate>
<Headertemplate>
</Headertemplate>
</ASP: templatefield>
</Columns>
</ASP: gridview>

To show you how to obtain the selected checkbox, you can add a button. When you select the option in the gridview and click this button, you can output the options selected by the user, write the following code in the button click event:

For (INT I = 0; I <gridview1.rows. Count; I ++)
{
Gridviewrow ROW = gridview1.rows [I];
Bool ischecked = (checkbox) Row. findcontrol ("chkselect"). checked;
If (ischecked)
{
Str. append (gridview1.rows [I]. cells [2]. Text );
}
}
Response. Write (Str. tostring ());

Next, we will add a select all box. When you select this box, you can select all the checkbox in the gridview. First, we will design the headtemplate as follows:

<Headertemplate>
<Input id = "chkall" onclick = "javascript: selectallcheckboxes (this);" runat = "server" type = "checkbox"/>
</Headertemplate>

The javascript code is as follows:

<Script language = JavaScript>
Function selectallcheckboxes (spanchk ){
VaR oitem = spanchk. Children;
VaR thebox = (spanchk. type = "checkbox ")? Spanchk: spanchk. Children. item [0];
Xstate = thebox. checked;
Elm = thebox. Form. elements;
For (I = 0; I <Elm. length; I ++)
If (ELM [I]. type = "checkbox" & elm [I]. ID! = Thebox. ID)
{
If (ELM [I]. Checked! = Xstate)
Elm [I]. Click ();
}
}
</SCRIPT>

3. Processing of deleting records in the gridview

In the gridview, we all hope that a prompt box will be prompted when deleting the record, which can be easily implemented in Asp.net 1.1. How can we implement it in Asp.net 2.0? The following example shows how to design the following code on the HTML page:

<Asp: gridview datakeynames = "categoryid" id = "gridview1" runat = "server" placement = "false" onrowcommand = "gridview1_rowcommand" onrowdatabound = "inline" onrowdeleted = "inline" onrowdeleting = "inline "">
<Columns>
<Asp: boundfield datafield = "categoryid" headertext = "categoryid"/>
<Asp: boundfield datafield = "categoryname" headertext = "categoryname"/>
<Asp: templatefield headertext = "select">
<Itemtemplate>
<Asp: linkbutton id = "linkbutton1" commandargument = '<% # eval ("categoryid") %> 'commandname = "delete" runat = "server"> Delete </ASP: linkbutton>
</Itemtemplate>
</ASP: templatefield>
</Columns>
</ASP: gridview>

In the above Code, we set a link linkbutton, in which commandname is specified as "delete", and commandargument is the ID number of the record to be deleted, note that once the commandname is set to delete, The gridview_rowcommand and gridview_row_deleting events in the gridview will be triggered by the operator. We will handle the rowdatabound event:

Protected void gridview1_rowdatabound (Object sender, gridviewroweventargs E)
{
If (E. Row. rowtype = datacontrolrowtype. datarow)
{
Linkbutton L = (linkbutton) E. Row. findcontrol ("linkbutton1 ");
L. Attributes. Add ('onclick "," javascript: Return "+" Confirm ("Do you want to delete this record? "+
Databinder. eval (E. Row. dataitem, "ID") + "')");
}
}

In this Code, first check whether it is a datarow. If yes, obtain each linkbutton and add the client code to it, which is similar to Asp.net 1.1.

After the user selects confirm deletion, there are two ways to proceed with subsequent deletion, because we set the delete button to delete, method 1: Write the following code in the row_command event:

Protected void gridview1_rowcommand (Object sender, gridviewcommandeventargs E)
{
If (E. commandname = "delete ")
{
Int id = convert. toint32 (E. commandargument );
// Special process for deleting records
Deleterecordbyid (ID );
}
}

Another method is to use the row_deletting event of the gridview. Add <asp: gridview datakeynames = "categoryid" id = "gridview1" runat = "server" autogeneratecolumns = "false" onrowcommand = "gridview1_rowcommand" onrowdatabound = "inline" onrowdeleting = "inline">
Then add the row_deleting event:

Protected void gridview1_rowdeleting (Object sender, gridviewdeleteeventargs E)
{
Int categoryid = (INT) gridview1.datakeys [E. rowindex]. value;
Deleterecordbyid (categoryid );
}

Note that datakeynames must be set as the number of the record to be deleted. Here is the categoryid.

  Summary

In this article, we continue to explore some usage of the gridview control, such as export to excel, processing When deleting records, and how to access the controls in the gridview.

 
Related Article

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.