Data manipulation techniques in the GridView of asp.net2.0

Source: Internet
Author: User
Tags continue eval html page tostring
Asp.net| Tips | The new GridView control in Data asp.net 2.0 is a very powerful data display control that shows many of the basic usage and techniques in the previous series (see the GridView control Advanced techniques in <<asp.net 2.0) , <<asp.net2.0 uses the GridView to realize the master-slave relationship > >). In this article, you will continue to explore the techniques involved.

   one, the content in the GridView Export to Excel

In daily work, it's often important to export the contents of the GridView to an Excel report, and in ASP.net 2.0, it's also easy to export the contents of the entire GridView to an Excel report, as described in the following ways:

First, create a 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"
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 Customers";
SqlConnection myconnection = new SqlConnection (ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter (query, MyConnection);
DataSet ds = new DataSet ();
Ad. Fill (ds, "Customers");
Gridview1.datasource = ds;
Gridview1.databind ();
}

public override void Verifyrenderinginserverform (Control control)
{
Confirms that a HtmlForm control are rendered for
}

protected void Button1_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 (which is used to export to Excel). Here use Response.AddHeader ("Content-disposition", "Attachment;filename=exporttoexcel.xls"); To specify the file name of the Excel that will be exported, this is Exporttoexcel.xls. Note that because the contents of the GridView may be paginated, the AllowPaging property of the GridView is set to False for each time you export Excel, and then the GridView of the current page is exported through page flow to Excel. Finally, reset its AllowPaging property. Also note that you want to write an empty Verifyrenderinginserverform method (which must be written) to make sure that the HtmlForm control is rendered for the specified ASP.net server control at run time.

   Ii. accessing various controls in the GridView

In the GridView, often access to the various types of controls, such as Dropdownlist,radiobutton,checkbox, and so on, the following summarized in the GridView access to various types of control methods.

First look at how to access the DropDownList control in the GridView. Assuming that in a gridviw, each record in the presentation requires the user to select the contents of the DropDownList control in a Drop-down selection, you can use the following code to click the button when the user chooses the options for the DropDownList control in the GridView The system prints out which DropDownList controls the user has selected 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 code above first returns the data from the Tblphone table in the database as a dataset. Then in the ItemTemplate of the page, the following design:

<ItemTemplate>
<asp:dropdownlist id= "DropDownList1" runat= "Server" datasource= "<%# populatedropdownlist ()%>"
Datatextfield= "Phone" DataValueField = "Phoneid"
</asp:DropDownList>
</ItemTemplate>
Notice here that the DataSource property of the DropDownList control binds the dataset just returned (the Populatedropdownlist () method is invoked). Also, be careful to set the DataTextField and DataValueField properties.

Then, in the event of the button, write the following code:

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 loops to get the value of the DropDownList control for each row and add the value to the final output in the string.

Next, let's look at how to access the CheckBox control in the GridView control. Often in the GridView control, you need to give users multiple choices of functionality, and this time you need to use a CheckBox control. First we set up a template column, which has a checkbox as follows:

<asp:gridview id= "GridView1" runat= "Server" allowpaging= "true" allowsorting= "true"
autogeneratecolumns= "False" datakeynames= "PersonID" datasourceid= "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>
In order to explain how to get the checkbox selected by the user, you can add a button that, when the user selects the option in the GridView, and then click the button, you can output the options selected by the user and write the following code in the Click event of the button:

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 add a selection box that selects all the checkboxes in the GridView when the user selects the box. First of all we have the following design in Headtemplate:

<HeaderTemplate>
<input id= "Chkall" runat= "Server" type= "checkbox"
</HeaderTemplate>
The code for the JavaScript section looks like this:

<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> iii. handling of deleted records in the GridView

In the GridView, we all want to be able to delete the record, pop-up prompts to prompt the box, in ASP.net 1.1, can be easily implemented, then in ASP.net 2.0 how to achieve it? The following examples illustrate that the following code is first designed in an HTML page:

<asp:gridview datakeynames= "CategoryID" id= "GridView1" runat= "Server" autogeneratecolumns= "False" onrowcommand= " Gridview1_rowcommand "onrowdatabound=" GridView1_RowDataBound "onrowdeleted=" gridview1_rowdeleted "OnRowDeleting=" Gridview1_rowdeleting ">
<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 code above, we set up a link LinkButton that specifies commandname as "delete", commandargument the ID number of the record to be deleted, Note that once the CommandName is set to the name of Delete, the Gridview_rowcommand and gridview_row_deleting events in the GridView will be triggered. We deal with its 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 DataRow, and then get each LinkButton, and then add client code for it, basic and ASP.net 1.1 of the practice is similar.

After that, when the user chooses to confirm the deletion, we have two ways to proceed with subsequent deletions because we set the delete button to delete, by writing 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 procedures for deleting records
Deleterecordbyid (ID);
}
}
Another method is to use the Row_deletting event of the GridView, first in the page HTML code, add <asp:gridview datakeynames= "CategoryID" id= "GridView1" runat= " Server "autogeneratecolumns=" False "onrowcommand=" Gridview1_rowcommand "onrowdatabound=" GridView1_RowDataBound " Onrowdeleting= "Gridview1_rowdeleting" >
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 this must set the DataKeyNames to the number of the record you want to delete, here is CategoryID.

   Summary

In this article, you continue to explore some of the uses of the GridView control, such as exporting to Excel, processing when you delete records, and accessing 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.