A flexible grasp of the various uses of the GridView control in asp.net (next) _ Practical skills

Source: Internet
Author: User
Tags urlencode xmlns

Continue the study of the previous article, "Flexible mastery of the asp.net in the GridView control of a variety of ways to use (above)", on this basis to consolidate the control of the GridView operation, a higher level.

11.GridView implementation uses "..." instead of super long string:
Effect Chart:

Workaround: filter each row after data binding

for (int i = 0; I <= gridview1.rows.count-1; i++)
{
DataRowView mydrv;
string Gintro;
if (Gridview1.pageindex = = 0)
{
mydrv = myds. Tables["Flying Fox Studio"]. defaultview[i];//table name
Gintro = convert.tostring (mydrv["Home Address");//The field to be processed
gridview1.rows[i]. CELLS[3]. Text = SubStr (Gintro, 2);
}
else
{
mydrv = myds. Tables["Flying Fox Studio"]. Defaultview[i + (5 * gridview1.pageindex)];
Gintro = convert.tostring (mydrv["Home Address");
Gridview1.rows[i]. CELLS[3]. Text = SubStr (Gintro, 2);
}
}

Method to invoke:

public string SubStr (string sstring, int Nleng)
{
if (sstring.length <= Nleng)
{return
sstring;
}
string snewstr = sstring.substring (0, Nleng);
Snewstr = Snewstr + "...";
return snewstr;
}

Background All code:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;

Using System.Data.SqlClient;
Public partial class _default:system.web.ui.page {SqlConnection sqlcon;
SqlCommand sqlcom; String Strcon = "Data source= (local);D atabase= North Wind trade; Uid=sa;
Pwd=sa "; protected void Page_Load (object sender, EventArgs e) {if (!
IsPostBack) {viewstate["SortOrder"] = "identity card number";
viewstate["Orderdire"] = "ASC";
Bind (); } protected void Gridview1_rowediting (object sender, GridViewEditEventArgs e) {gridview1.editindex = E.neweditindex; bi
nd (); } protected void Gridview1_rowdeleting (object sender, Gridviewdeleteeventargs e) {string sqlstr = "Delete from flying Fox Studio wher E id number = ' "+ Gridview1.datakeys[e.rowindex].
Value.tostring () + "'";
Sqlcon = new SqlConnection (Strcon);
sqlcom = new SqlCommand (Sqlstr,sqlcon); Sqlcon.
Open (); Sqlcom. ExecutenOnquery (); Sqlcon.
Close ();
Bind (); } protected void Gridview1_rowupdating (object sender, Gridviewupdateeventargs e) {sqlcon = new SqlConnection (Strcon); str ing sqlstr = "Update flying fox studio Set name = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[1]. Controls[0]). Text.tostring (). Trim () + "', home address = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[3]. Controls[0]). Text.tostring (). Trim () + "' WHERE id number = ' + Gridview1.datakeys[e.rowindex]."
Value.tostring () + "'";
Sqlcom=new SqlCommand (Sqlstr,sqlcon); Sqlcon.
Open (); Sqlcom.
ExecuteNonQuery (); Sqlcon.
Close ();
Gridview1.editindex =-1;
Bind (); } protected void Gridview1_rowcancelingedit (object sender, Gridviewcancelediteventargs e) {gridview1.editindex =-1; bin
D ();
public void Bind () {String sqlstr = ' SELECT Top 5 * Fly Fox Studio '; Sqlcon = new SqlConnection (Strcon);
SqlDataAdapter Myda = new SqlDataAdapter (Sqlstr, Sqlcon);
DataSet myds = new DataSet (); Sqlcon.
Open (); Myda.
Fill (myDS, "Flying Fox Studio");
Gridview1.datasource = myds; Gridview1.datakeynames = NEW string[] {"id card number"};
Gridview1.databind (); 
for (int i = 0; I &lt;= gridview1.rows.count-1 i++) {DataRowView mydrv; string Gintro; if (gridview1.pageindex = 0) { Mydrv = myDS. Tables["Flying Fox Studio"].
Defaultview[i];
Gintro = convert.tostring (mydrv["Home Address"); Gridview1.rows[i]. CELLS[3].
Text = SubStr (Gintro, 2); else {mydrv = myds. Tables["Flying Fox Studio"].
Defaultview[i + (5 * gridview1.pageindex)];
Gintro = convert.tostring (mydrv["Home Address"); Gridview1.rows[i]. CELLS[3].
Text = SubStr (Gintro, 2); }} sqlcon.
Close (); public string SubStr (string sstring, int Nleng) {if (sstring.length &lt;= Nleng) {return sstring;} string snewstr = S
String.substring (0, Nleng);
Snewstr = Snewstr + "...";
return snewstr; } protected void GridView1_RowDataBound (object sender, GridViewRowEventArgs e) {//if is bound data row if (E.row.rowtype = = Datacontr Olrowtype.datarow) {////When the mouse passes, the row background color changes//e.row.attributes.add ("onmouseover", "This.style.backgroundcolor= ' #E6F5FA")
; When the mouse moves out, the row background color changes//e.row.attributes.add ("onmouseout", "this.styLe.backgroundcolor= ' #FFFFFF '); When there is edit column, avoid error, to add RowState judgment//if (e.row.rowstate = = Datacontrolrowstate.normal | | e.row.rowstate = datacontrolrowstate.alternate)//{//((LinkButton) e.row.cells[6]. Controls[0]). Attributes.Add ("onclick", "Javascript:return Confirm" (' You are sure to delete:/"" + e.row.cells[1].
Text + "/"? ') "); } if (E.row.rowindex!=-1) {int id = e.row.rowindex + 1; e.row.cells[0]. Text = ID.
ToString ();

 }

}
}

12.GridView General line wrapping and force wrapping:

Effect Chart:


First set <asp:boundfield datafield= "Home Address" headertext= "Home Address" itemstyle-width= "/>"
In the GridView, there is a column of bound data that is long, displayed in a row, and the page is wide.
The reason is that the consecutive English paragraph is caused by a whole, in the rowdatabound added a sentence of e.row.cells[2]. Style.add ("Word-break", "Break-all") is OK.

If you want to add this property to all columns:

protected void Page_Load (object sender, EventArgs e)
{
//normal line wrap
GridView1.Attributes.Add ("style", " Word-break:keep-all;word-wrap:normal ");
The following line is the automatic line wrapping
GridView1.Attributes.Add ("style", "Word-break:break-all;word-wrap:break-word");
if (! IsPostBack)
{
bind ();//Call Data binding can
}
}

All in all: Use the CSS Word-break:break-all;word-wrap:break-word attribute, this attribute is universal for the stubborn South line of the problem can be resolved, not limited to the GridView.

13.GridView display hides a column:
This program for the moon, different from other online methods, I think with a checkbox more humane, so that you can hide unnecessary columns, so that users choose the column they want to appear in the processing of multiple columns This is a good solution!

Effect Chart:

Figure 1-Start

Figure 2-After clicking the checkbox shown

Solution:

public void bind ()
{
String sqlstr = ' SELECT Top 5 * from flying Fox Studio ';
Sqlcon = new SqlConnection (Strcon);
SqlDataAdapter Myda = new SqlDataAdapter (Sqlstr, Sqlcon);
DataSet myds = new DataSet ();
Sqlcon. Open ();
Myda. Fill (myDS, "Flying Fox Studio");
Gridview1.datasource = myds;
Gridview1.datakeynames = new string[] {"Identity card number"};
Gridview1.databind ();
Sqlcon. Close ();
GRIDVIEW1.COLUMNS[3]. Visible = false;//A start hide
checkbox1.checked = false;//if not, then the code behind will put him true
}

double click on CheckBox1, Write the code in the CheckedChanged method, and the final code is as follows:
protected void checkbox1_checkedchanged (object sender, EventArgs e)
{
Gridview1.columns[3]. visible=! GRIDVIEW1.COLUMNS[3]. Visible;
Response.Write (The 4th column of the GridView1 now shows a hidden state: "+gridview1.columns[3]." Visible.tostring ());
}

Note: CheckBox1 's AutoPostBack to true!.

Backstage all the code is as follows:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;

Using System.Data.SqlClient;
Public partial class _default:system.web.ui.page {SqlConnection sqlcon;
SqlCommand sqlcom; String Strcon = "Data source= (local);D atabase= North Wind trade; Uid=sa;
Pwd=sa "; protected void Page_Load (object sender, EventArgs e) {if (!
IsPostBack) {viewstate["SortOrder"] = "identity card number";
viewstate["Orderdire"] = "ASC";
Bind (); } protected void Gridview1_rowediting (object sender, GridViewEditEventArgs e) {gridview1.editindex = E.neweditindex; bi
nd (); } protected void Gridview1_rowdeleting (object sender, Gridviewdeleteeventargs e) {string sqlstr = "Delete from flying Fox Studio wher E id number = ' "+ Gridview1.datakeys[e.rowindex].
Value.tostring () + "'";
Sqlcon = new SqlConnection (Strcon);
sqlcom = new SqlCommand (Sqlstr,sqlcon); Sqlcon.
Open (); Sqlcom. ExecutenOnquery (); Sqlcon.
Close ();
Bind (); } protected void Gridview1_rowupdating (object sender, Gridviewupdateeventargs e) {sqlcon = new SqlConnection (Strcon); str ing sqlstr = "Update flying fox studio Set name = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[1]. Controls[0]). Text.tostring (). Trim () + "', home address = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[3]. Controls[0]). Text.tostring (). Trim () + "' WHERE id number = ' + Gridview1.datakeys[e.rowindex]."
Value.tostring () + "'";
Sqlcom=new SqlCommand (Sqlstr,sqlcon); Sqlcon.
Open (); Sqlcom.
ExecuteNonQuery (); Sqlcon.
Close ();
Gridview1.editindex =-1;
Bind (); } protected void Gridview1_rowcancelingedit (object sender, Gridviewcancelediteventargs e) {gridview1.editindex =-1; bin
D ();
public void Bind () {String sqlstr = ' SELECT Top 5 * Fly Fox Studio '; Sqlcon = new SqlConnection (Strcon);
SqlDataAdapter Myda = new SqlDataAdapter (Sqlstr, Sqlcon);
DataSet myds = new DataSet (); Sqlcon.
Open (); Myda.
Fill (myDS, "Flying Fox Studio");
Gridview1.datasource = myds; Gridview1.datakeynames = NEW string[] {"id card number"};
Gridview1.databind (); Sqlcon.
Close (); GRIDVIEW1.COLUMNS[3].
Visible = false;
checkbox1.checked = false; } protected void Checkbox1_checkedchanged (object sender, EventArgs e) {gridview1.columns[3]. visible=! GRIDVIEW1.COLUMNS[3].
Visible; Response.Write (The 4th column of the GridView1 now shows a hidden state: "+gridview1.columns[3]."
Visible.tostring ());

 }
}

Foreground code:

&lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;html xmlns=" http://www.w3.org/1999/xhtml "&gt; &lt;head runat=" Server "&gt; &lt;title&gt;gridview Show hidden Columns &lt;/ title&gt; &lt;/head&gt; &lt;body style= "font-size=12px" &gt; &lt;form id= "Form1" runat= "Server" &gt; &lt;div&gt; &lt;asp : GridView id= "GridView1" runat= "Server" cellpadding= "3" onrowdeleting= "gridview1_rowdeleting" onrowediting= " Gridview1_rowediting "onrowupdating=" gridview1_rowupdating "onrowcancelingedit=" Gridview1_rowcancelingedit " Backcolor= "White" bordercolor= "#CCCCCC" borderstyle= "None" borderwidth= "1px" font-size= "12px" &gt; &lt;footerstyle Backcolor= "White" forecolor= "#000066"/&gt; &lt;Columns&gt; &lt;asp:boundfield datafield= "ID number" headertext= "number" readonly= "True"/&gt; &lt;asp:boundfield datafield= "name" headertext= "user name"/&gt; &lt;asp:boundfield DataField= "ZIP code" headertext= "Postal Code" sortexpression= "/&gt; &lt;asp:boundfield datafield=" Home Address " headertext= "Home Address"/&gt; &lt;asp:commandfield headertext= "select" showselectbutton= "True"/&gt; &lt;asp:commandfield headertext= "edit" showeditbutton= "true"/&gt; &lt;asp:commandfield headertext= "Delete" showdeletebutton= "true"/&gt; &lt;/ columns&gt; &lt;rowstyle forecolor= "#000066"/&gt; &lt;selectedrowstyle backcolor= "True" font-bold= "#669999" forecolor= "White"/&gt; &lt;pagerstyle backcolor= ' white ' forecolor= ' #000066 ' horizontalalign= ' left '/&gt; &lt; HeaderStyle backcolor= "#006699" font-bold= "True" forecolor= "white"/&gt; &lt;/asp:GridView&gt; &lt;asp:checkbox id= " CheckBox1 "runat=" Server "font-size=" 12px "oncheckedchanged=" checkbox1_checkedchanged "text=" Show hidden Home Address "/&gt;&lt;/ div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;

14.GridView pop-up new page/popup set size position new window:

Effect Chart:

Solution One: Simple method, new window not fixed size

&lt;asp:gridview id= "GridView1" runat= "Server" cellpadding= "3" onrowdeleting= "gridview1_rowdeleting" "onrowediting=" Gridview1_rowediting "onrowupdating=" gridview1_rowupdating "onrowcancelingedit=" Gridview1_rowcancelingedit " Backcolor= "White" bordercolor= "#CCCCCC" borderstyle= "None" borderwidth= "1px" font-size= "12px" &gt; &lt;footerstyle Backcolor= "White" forecolor= "#000066"/&gt; &lt;Columns&gt; &lt;asp:boundfield datafield= "ID number" headertext= "number" readonly= "True"/&gt; &lt;asp:boundfield datafield= Postal Code "headertext=" Postal Code "sortexpression=/&gt;: BoundField datafield= "Home Address" headertext= "Home Address"/&gt; &lt;asp:hyperlinkfield headertext= "name" text= "name" datanavigateurlfields= "name" datanavigateurlformatstring= "Default6.aspx?"
goodsid={0} "target=" mainframe "navigateurl=" ~/default6.aspx "datatextfield=" Name &gt; &lt;/asp:HyperLinkField&gt; &lt;asp:commandfield headertext= "Select" showselectbutton= "True"/&gt; &lt;asp:commandfield headertext= "edit" showeditbutton= "True"/&gt; &lt;asp:commandfielD headertext= "Delete" showdeletebutton= "True"/&gt; &lt;/Columns&gt; &lt;rowstyle forecolor= "#000066"/&gt; &lt; SelectedRowStyle backcolor= "#669999" font-bold= "True" forecolor= "white"/&gt; &lt;pagerstyle backcolor= "White" Forecolor= "#000066" horizontalalign= "left"/&gt; &lt;headerstyle backcolor= "#006699" font-bold= "True" forecolor= "
 White "/&gt; &lt;/asp:GridView&gt;

DataNavigateUrlFields is the field name of the link, datanavigateurlformatstring is the path.

Scenario two: Precise control of pop-up window size position

<asp:hyperlinkcolumn datanavigateurlfield= "EmployeeID" datanavigateurlformatstring= "javascript:varwin= window.open (' detail.aspx?id={0} ', null, ' width=300,height=200 '); window. Close (); "
Datatextfield= "LastName" headertext= "LastName" ></asp:HyperLinkColumn>

15.GridView Fixed header (not JavaScript only with css!, very useful):

Effect Chart:

Code:

&lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;html xmlns=" http://www.w3.org/1999/xhtml "&gt; &lt;head runat=" Server "&gt; &lt;title&gt;gridview fixed header &lt;/ Title&gt; &lt;style&gt;.

freezing {position:relative; table-layout:fixed; Top:expression_r (this.offsetParent.scrollTop); z-index:10;} .
Freezing th{text-overflow:ellipsis;overflow:hidden;white-space:nowrap;padding:2px;} &lt;/style&gt; &lt;/head&gt; &lt;body style= "font-size=12px" &gt; &lt;form id= "Form1" runat= "Server" &gt; &lt;div style= "overflow-y: scroll; height:200px;width:300px "id=" Dvbody "&gt; &lt;asp:gridview id=" GridView1 "runat=" Server "cellpadding=" 3 " onrowdeleting= "gridview1_rowdeleting" onrowediting= "gridview1_rowediting" onrowupdating= "GridView1_RowUpdating" onrowcancelingedit= "Gridview1_rowcancelingedit" backcolor= "white" bordercolor= "#CCCCCC" borderstyle= "None" Borderwidth= "1px" font-size= "12px" onrowcreated= "gridview1_rowcreated"&gt; &lt;footerstyle backcolor= "White" forecolor= "#000066"/&gt; &lt;Columns&gt; &lt;asp:boundfield datafield= "ID card number" headertext= "number" readonly= "True"/&gt; &lt;asp:boundfield datafield= "headertext=" Postal Code "sortexpression=" Postal Code "/ &gt; &lt;asp:boundfield datafield= "Home Address" headertext= "Home Address"/&gt; &lt;asp:boundfield datafield= "name" headertext= "name"/ &gt; &lt;/Columns&gt; &lt;rowstyle forecolor= "#000066"/&gt; &lt;selectedrowstyle backcolor= "#669999" font-bold= "True "Forecolor=" white "/&gt; &lt;pagerstyle backcolor=" white "forecolor=" #000066 "horizontalalign=" left "cssclass=" Ms-formlabel datagridfixedheader "/&gt; &lt;headerstyle backcolor=" "#006699" font-bold= "True" forecolor= "white"

 cssclass= "Freezing"/&gt; &lt;/asp:GridView&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;

Usage: CSS set as above style, HeaderStyle plus cssclass= "freezing, nested gridview div Set height width <div style=" overflow-y: scroll; height:200px;width:200px ">

16.GridView Merge Header multiple header error-free perfect version (to combine 3 columns, 3 rows, for example)

Effect Chart:

Background code:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Data.SqlClient;
Using System.Drawing;
Public partial class _default:system.web.ui.page {SqlConnection sqlcon;
SqlCommand sqlcom; String Strcon = "Data source= (local);D atabase= North Wind trade; Uid=sa;
Pwd=sa "; protected void Page_Load (object sender, EventArgs e) {if (!

IsPostBack) {bind (); } protected void Gridview1_rowediting (object sender, GridViewEditEventArgs e) {gridview1.editindex = E.neweditindex; bi
nd (); } protected void Gridview1_rowupdating (object sender, Gridviewupdateeventargs e) {sqlcon = new SqlConnection (Strcon); str ing sqlstr = "Update flying fox studio Set name = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[1]. Controls[0]). Text.tostring (). Trim () + "', home address = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[3]. Controls[0]). Text.tostring (). Trim () + "' WHERE id number = ' + Gridview1.datakeys[e.rowindex]."
Value.tostring () + "'";
Sqlcom=new SqlCommand (Sqlstr,sqlcon); Sqlcon.
Open (); Sqlcom.
ExecuteNonQuery (); Sqlcon.
Close ();
Gridview1.editindex =-1;
Bind (); } protected void Gridview1_rowcancelingedit (object sender, Gridviewcancelediteventargs e) {gridview1.editindex =-1; bin
D ();
public void Bind () {String sqlstr = ' Select Top # from flying Fox Studio '; Sqlcon = new SqlConnection (Strcon);
SqlDataAdapter Myda = new SqlDataAdapter (Sqlstr, Sqlcon);
DataSet myds = new DataSet (); Sqlcon.
Open (); Myda.
Fill (myDS, "Flying Fox Studio");
Gridview1.datasource = myds;
Gridview1.datakeynames = new string[] {"Identity card number"};
Gridview1.databind (); Sqlcon.
Close (); //This is the solution protected void gridview1_rowcreated (object sender, GridViewRowEventArgs e) {switch (e.row.rowtype) {case D
Atacontrolrowtype.header:///First row header tablecellcollection Tcheader = e.row.cells;
Tcheader.clear ();
Tcheader.add (New Tableheadercell ()); Tcheader[0]. Attributes.Add ("RowSpan", "3"); Cross Row TcheadEr[0].
Attributes.Add ("bgcolor", "white"); Tcheader[0].
Text = "";
Tcheader.add (New Tableheadercell ()); TCHEADER[1].
Attributes.Add ("bgcolor", "Red"); TCHEADER[1]. Attributes.Add ("colspan", "6"); Cross column Tcheader[1].

Text = "All information &lt;/th&gt;&lt;/tr&gt;&lt;tr&gt;";
Second row header Tcheader.add (new Tableheadercell ()); TCHEADER[2].
Attributes.Add ("bgcolor", "darkseagreen"); TCHEADER[2].
Text = "ID card number";
Tcheader.add (New Tableheadercell ()); TCHEADER[3].
Attributes.Add ("bgcolor", "lightsteelblue"); TCHEADER[3].
Attributes.Add ("colspan", "2"); TCHEADER[3].
Text = "basic Information";
Tcheader.add (New Tableheadercell ()); TCHEADER[4].
Attributes.Add ("bgcolor", "darkseagreen"); TCHEADER[4].
Text = "welfare";
Tcheader.add (New Tableheadercell ()); TCHEADER[5].
Attributes.Add ("bgcolor", "lightsteelblue"); TCHEADER[5].
Attributes.Add ("colspan", "2"); TCHEADER[5].

Text = "Contact Method &lt;/th&gt;&lt;/tr&gt;&lt;tr&gt;";
Third row header Tcheader.add (new Tableheadercell ()); TCHEADER[6].
Attributes.Add ("bgcolor", "khaki"); TCHEADER[6].
Text = "ID card number"; TcheadeR.add (New Tableheadercell ()); TCHEADER[7].
Attributes.Add ("bgcolor", "khaki"); TCHEADER[7].
Text = "name";
Tcheader.add (New Tableheadercell ()); TCHEADER[8].
Attributes.Add ("bgcolor", "khaki"); TCHEADER[8].
Text = "Date of birth";
Tcheader.add (New Tableheadercell ()); TCHEADER[9].
Attributes.Add ("bgcolor", "khaki"); TCHEADER[9].
Text = "Salary";
Tcheader.add (New Tableheadercell ()); TCHEADER[10].
Attributes.Add ("bgcolor", "khaki"); TCHEADER[10].
Text = "Home Address";
Tcheader.add (New Tableheadercell ()); TCHEADER[11].
Attributes.Add ("bgcolor", "khaki"); TCHEADER[11].
Text = "Postal Code";
Break

 }
}
}

Foreground:

&lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;html xmlns=" http://www.w3.org/1999/xhtml "&gt; &lt;head runat=" Server "&gt; &lt;title&gt;gridview merge Multiple header headers &lt;/title&gt; &lt;/head&gt; &lt;body &gt; &lt;form id= "Form1" runat= "Server" &gt; &lt;div &gt; &lt;asp:gridview id= " GridView1 "runat=" Server "cellpadding=" 3 "onrowediting=" gridview1_rowediting "onrowupdating=" gridview1_rowupdating "Onrowcancelingedit=" Gridview1_rowcancelingedit "backcolor=" White "bordercolor=" "#CCCCCC" borderstyle= "None" Borderwidth= "1px" font-size= "12px" onrowcreated= "gridview1_rowcreated" &gt; &lt;footerstyle backcolor= "White" Forecolor= "#000066"/&gt; &lt;Columns&gt; &lt;asp:commandfield headertext= edit showeditbutton= "True"/&gt; &lt;asp: BoundField datafield= "ID number" headertext= "number" readonly= "True"/&gt; &lt;asp:boundfield "name" datafield= "name"/ &gt; &lt;asp:boundfield datafield= "Birth date" headertext= "Postal code"/&gt; &lt;asp:boundfiEld datafield= "Starting salary" headertext= "starting salary"/&gt; &lt;asp:boundfield datafield= "Home Address" headertext= "Home Address"/&gt; &lt;asp: BoundField datafield= "headertext=" Postal code "/&gt; &lt;/Columns&gt; &lt;rowstyle forecolor=" #000066 "/&gt; &lt; SelectedRowStyle backcolor= "#669999" font-bold= "True" forecolor= "white"/&gt; &lt;pagerstyle backcolor= "White" Forecolor= "#000066" horizontalalign= "left" cssclass= "Ms-formlabel datagridfixedheader"/&gt; &lt;headerstyle Backcolor= "#006699" font-bold= "True" forecolor= "white"/&gt; &lt;/asp:GridView&gt; &lt;/div&gt; &lt;/form&gt; &lt;/ Body&gt; &lt;/html&gt;

17.GridView Highlight a cell (for example, the amount is less than the number, the score failed, etc.)

Effect Chart:

Solution: Mainly after binding filter

Gridview1.databind ();
for (int i = 0; I <= gridview1.rows.count-1 i++)
{
DataRowView mydrv = myds. Tables["Flying Fox Studio"]. Defaultview[i];
String score = convert.tostring (mydrv["starting salary"]);
if (convert.todouble (score) < 34297.00)//Everyone here according to the specific situation set may ToInt32 and so on
{
gridview1.rows[i]. CELLS[4]. BackColor = System.Drawing.Color.Red;
}
Sqlcon. Close ();

All background code:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Data.SqlClient;

Using System.Drawing;
Public partial class Default7:System.Web.UI.Page {SqlConnection sqlcon;
SqlCommand sqlcom; String Strcon = "Data source= (local);D atabase= North Wind trade; Uid=sa;
Pwd=sa "; protected void Page_Load (object sender, EventArgs e) {if (!

IsPostBack) {bind (); } protected void Gridview1_rowediting (object sender, GridViewEditEventArgs e) {gridview1.editindex = E.neweditindex; bi
nd (); } protected void Gridview1_rowupdating (object sender, Gridviewupdateeventargs e) {sqlcon = new SqlConnection (Strcon); str ing sqlstr = "Update flying fox studio Set name = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[1]. Controls[0]). Text.tostring (). Trim () + "', home address = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[3]. Controls[0]). Text.tostring (). TrIm () + "' WHERE id number = ' + Gridview1.datakeys[e.rowindex]."
Value.tostring () + "'";
sqlcom = new SqlCommand (sqlstr, Sqlcon); Sqlcon.
Open (); Sqlcom.
ExecuteNonQuery (); Sqlcon.
Close ();
Gridview1.editindex =-1;
Bind (); } protected void Gridview1_rowcancelingedit (object sender, Gridviewcancelediteventargs e) {gridview1.editindex =-1; bin
D ();
public void Bind () {String sqlstr = ' Select Top # from flying Fox Studio '; Sqlcon = new SqlConnection (Strcon);
SqlDataAdapter Myda = new SqlDataAdapter (Sqlstr, Sqlcon);
DataSet myds = new DataSet (); Sqlcon.
Open (); Myda.
Fill (myDS, "Flying Fox Studio");
Gridview1.datasource = myds;
Gridview1.datakeynames = new string[] {"Identity card number"};
Gridview1.databind (); for (int i = 0; I &lt;= gridview1.rows.count-1 i++) {DataRowView mydrv = myds. Tables["Flying Fox Studio"].
Defaultview[i];
String score = convert.tostring (mydrv["starting salary"]); if (convert.todouble (score) &lt; 34297.00)//Everyone here according to the specific situation set may ToInt32 and so on {gridview1.rows[i]. CELLS[4].
BackColor = System.Drawing.Color.Red; }} sqlcon.
Close ();

 }
}

Foreground code:

&lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;html xmlns=" http://www.w3.org/1999/xhtml "&gt; &lt;head id=" Head1 "runat=" Server "&gt; &lt;title&gt; The GridView highlights a cell clear moon http://blog.csdn.net/21aspnet &lt;/title&gt; &lt;/head&gt; &lt;body &gt; &lt;form id= "Form1" runat= "Server" &gt; &lt;div &gt; &lt;asp:gridview id= "GridView1" runat= "Server" cellpadding= "3" onrowediting= " Gridview1_rowediting "onrowupdating=" gridview1_rowupdating "onrowcancelingedit=" Gridview1_rowcancelingedit " Backcolor= "White" bordercolor= "#CCCCCC" borderstyle= "None" borderwidth= "1px" font-size= "12px" &gt; &lt;footerstyle Backcolor= "White" forecolor= "#000066"/&gt; &lt;Columns&gt; &lt;asp:commandfield headertext= "edit" showeditbutton= " True "/&gt; &lt;asp:boundfield datafield=" ID number "headertext=" number "readonly=" true "/&gt; &lt;asp:boundfield DataField=" Name "headertext=" name "/&gt; &lt;asp:boundfield datafield=" date of birth headertext= "zip code"/&gt; &lt;Asp:boundfield datafield= "Starting salary" headertext= "Starting salary" dataformatstring= "{0:c}" htmlencode= "false"/&gt;
datafield= "Home Address" headertext= "Home Address"/&gt; &lt;asp:boundfield datafield= "headertext=" Postal code "/&gt; &lt;/Columns&gt; &lt;rowstyle forecolor= "#000066"/&gt; &lt;selectedrowstyle backcolor= "#669999" font-bold= "True" forecolor= "white"/ &gt; &lt;pagerstyle backcolor= "White" forecolor= "the #000066" horizontalalign= "left" cssclass= "Ms-formlabel Datagridfixedheader "/&gt; &lt;headerstyle backcolor=" #006699 "font-bold=" True "forecolor=" white "/&gt; &lt;/asp:
 gridview&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;

18.GridView adding automatic summation to mean subtotal

Effect Chart:

Solution:

private double sum = 0;//The data of the specified column and, depending on the circumstances, you may be dealing with an int
protected void GridView1_RowDataBound (object sender, GridViewRowEventArgs e)
{

if (e.row.rowindex >= 0)
{
sum = convert.todouble (e.row.cells[6]. Text);
}
else if (E.row.rowtype = = Datacontrolrowtype.footer)
{
e.row.cells[5]. Text = "Total pay for:";
E.ROW.CELLS[6]. Text = Sum. ToString ();
E.ROW.CELLS[3]. Text = "Average pay for:";
E.ROW.CELLS[4]. Text = ((int) (Sum/gridview1.rows.count)). ToString ();

}
}

Background All code:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Data.SqlClient;

Using System.Drawing;
Public partial class Default7:System.Web.UI.Page {SqlConnection sqlcon;
SqlCommand sqlcom; String Strcon = "Data source= (local);D atabase= North Wind trade; Uid=sa;
Pwd=sa "; protected void Page_Load (object sender, EventArgs e) {if (!

IsPostBack) {bind (); } protected void Gridview1_rowediting (object sender, GridViewEditEventArgs e) {gridview1.editindex = E.neweditindex; bi
nd (); } protected void Gridview1_rowupdating (object sender, Gridviewupdateeventargs e) {sqlcon = new SqlConnection (Strcon); str ing sqlstr = "Update flying fox studio Set name = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[1]. Controls[0]). Text.tostring (). Trim () + "', home address = '" + (TextBox) (Gridview1.rows[e.rowindex). CELLS[3]. Controls[0]). Text.tostring (). TrIm () + "' WHERE id number = ' + Gridview1.datakeys[e.rowindex]."
Value.tostring () + "'";
sqlcom = new SqlCommand (sqlstr, Sqlcon); Sqlcon.
Open (); Sqlcom.
ExecuteNonQuery (); Sqlcon.
Close ();
Gridview1.editindex =-1;
Bind (); } protected void Gridview1_rowcancelingedit (object sender, Gridviewcancelediteventargs e) {gridview1.editindex =-1; bin
D ();
public void Bind () {String sqlstr = ' SELECT Top 5 * Fly Fox Studio '; Sqlcon = new SqlConnection (Strcon);
SqlDataAdapter Myda = new SqlDataAdapter (Sqlstr, Sqlcon);
DataSet myds = new DataSet (); Sqlcon.
Open (); Myda.
Fill (myDS, "Flying Fox Studio");
Gridview1.datasource = myds;
Gridview1.datakeynames = new string[] {"Identity card number"};
Gridview1.databind (); Sqlcon.
Close (); private double sum = 0;//The data of the specified column and protected void GridView1_RowDataBound (object sender, GridViewRowEventArgs e) {if (e). Row.rowindex &gt;= 0) {sum + = convert.todouble (E.row.cells[6].
Text); else if (E.row.rowtype = = Datacontrolrowtype.footer) {e.row.cells[5].
Text = "Total pay for:"; E.ROW.CELLS[6]. Text = Sum. ToSTring (); E.ROW.CELLS[3].
Text = "Average pay for:"; E.ROW.CELLS[4]. Text = ((int) (Sum/gridview1.rows.count)).

ToString ();

 }
}
}

Foreground: The only flower head is set showfooter= "True", otherwise the default header is hidden!

&lt;asp:gridview id= "GridView1" runat= "Server" cellpadding= "3" onrowediting= "gridview1_rowediting" "onrowupdating=" Gridview1_rowupdating "onrowcancelingedit=" Gridview1_rowcancelingedit "backcolor=" "White" BorderColor= "#CCCCCC" Borderstyle= "None" borderwidth= "1px" font-size= "12px" onrowdatabound= "GridView1_RowDataBound" showfooter= "True" &gt; &lt;footerstyle backcolor= "White" forecolor= "#000066"/&gt; &lt;Columns&gt; &lt;asp:commandfield headertext= "edit" Showeditbutton= "true"/&gt; &lt;asp:boundfield datafield= "ID number" headertext= "number" readonly= "true"/&gt; &lt;asp: BoundField datafield= "name" headertext= "name"/&gt; &lt;asp:boundfield datafield= "Birth date" headertext= "Zip Code"/&gt;: BoundField datafield= "Home Address" headertext= "Home Address"/&gt; &lt;asp:boundfield datafield= "Postal code" headertext= &lt; Asp:boundfield datafield= "Starting salary" headertext= "starting salary"/&gt; &lt;/Columns&gt; &lt;rowstyle forecolor= "#000066"/&gt; &lt; SelectedRowStyle backcolor= "#669999" font-bold= "True" forecolor= "white"/&gt; &lt;pagersTyle backcolor= "White" forecolor= "the #000066" horizontalalign= "left" cssclass= "Ms-formlabel datagridfixedheader"/&gt;
 &lt;headerstyle backcolor= "#006699" font-bold= "True" forecolor= "white"/&gt; &lt;/asp:GridView&gt;

19.GridView data import excel/excel data read into the GridView

Effect Chart:

Solution:
Add a button to the page, click the event adding the following method:

protected void Button1_Click (object sender, EventArgs e)
{
Export ("Application/ms-excel", "Student performance report. xls");
}

private void Export (String FileType, string FileName)
{
Response.Charset = "GB2312";
response.contentencoding = System.Text.Encoding.UTF7;
Response.appendheader ("Content-disposition", "attachment;filename=" + httputility.urlencode (filename, Encoding.UTF8). ToString ());
Response.ContentType = FileType;
This. EnableViewState = false;
StringWriter tw = new StringWriter ();
HtmlTextWriter HW = new HtmlTextWriter (TW);
Gridview1.rendercontrol (HW);
Response.Write (TW. ToString ());
Response.End ();
}
The control "GridView1" with the type "GridView" must be placed in a form tag that has a runat=server if there are no following methods public
override void Verifyrenderinginserverform (Control Control)
{
}

And the introduction of namespace IO and text because it's a file operation.

Background code:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Data.SqlClient;
Using System.Drawing;
Using System.IO;
Using System.Text;
Public partial class Default7:System.Web.UI.Page {SqlConnection sqlcon;
SqlCommand sqlcom; String Strcon = "Data source= (local);D atabase= North Wind trade; Uid=sa;
Pwd=sa "; protected void Page_Load (object sender, EventArgs e) {if (!

IsPostBack) {bind ();
} public void Bind () {String sqlstr = ' SELECT Top 5 * Fly Fox Studio '; Sqlcon = new SqlConnection (Strcon);
SqlDataAdapter Myda = new SqlDataAdapter (Sqlstr, Sqlcon);
DataSet myds = new DataSet (); Sqlcon.
Open (); Myda.
Fill (myDS, "Flying Fox Studio");
Gridview1.datasource = myds;
Gridview1.datakeynames = new string[] {"Identity card number"};
Gridview1.databind (); Sqlcon.
Close (); } protected void button1_click (object sender, EventArgs e) {Export ("ApplicatIon/ms-excel "," Student performance report. xls ");
private void Export (String FileType, String FileName) {Response.Charset = "GB2312";
response.contentencoding = System.Text.Encoding.UTF7; Response.appendheader ("Content-disposition", "attachment;filename=" + httputility.urlencode (filename, Encoding.UTF8).
ToString ());
Response.ContentType = FileType; This.
EnableViewState = false;
StringWriter tw = new StringWriter ();
HtmlTextWriter HW = new HtmlTextWriter (TW);
Gridview1.rendercontrol (HW); Response.Write (TW.
ToString ());
Response.End ();

 override void Verifyrenderinginserverform (control) {}}

Foreground:

&lt;asp:gridview id= "GridView1" runat= "Server" cellpadding= "3" backcolor= "white" bordercolor= "#CCCCCC" borderstyle= " None "borderwidth=" 1px "font-size=" 12px "&gt; &lt;footerstyle backcolor=" White "forecolor=" #000066 "/&gt; &lt;columns &gt; &lt;asp:boundfield datafield= "ID number" headertext= "number" readonly= "True"/&gt; &lt;asp:boundfield "name" headertext= "name"/&gt; &lt;asp:boundfield datafield= "Birth date" headertext= "Postal code"/&gt; &lt;asp:boundfield DataField= "Home Address" headertext= "Home Address"/&gt; &lt;asp:boundfield datafield= "headertext=" Postal code "/&gt; &lt;asp:boundfield DataField=" Starting salary " headertext= "Starting salary"/&gt; &lt;/Columns&gt; &lt;rowstyle forecolor= "#000066/&gt; &lt;selectedrowstyle backcolor=" #669999 "Font-bold=" True "forecolor=" white "/&gt; &lt;pagerstyle backcolor=" white "forecolor=" #000066 "horizontalalign=" left "Cssclass=" Ms-formlabel datagridfixedheader "/&gt; &lt;headerstyle backcolor=" #006699 "font-bold=" True "ForeColor=" White "/&gt; &lt;/asp:GridView&gt; &lt;asp:button id=" Button1 "Run"at= "Server" onclick= "Button1_Click" text= "Export"/&gt;

 

Code to read Excel data: This is simple.

Private DataSet CreateDataSource ()
{
string strcon;
Strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Server.MapPath ("Excel.xls") + "; Extended Properties=excel 8.0; ";
OleDbConnection olecon = new OleDbConnection (Strcon);
OleDbDataAdapter Myda = new OleDbDataAdapter ("SELECT * from [sheet1$]", Strcon);
DataSet myds = new DataSet ();
Myda. Fill (myds);
return myds;
}
protected void Button1_Click (object sender, EventArgs e)
{
Gridview1.datasource = CreateDataSource ();
Gridview1.databind ();
}

3 wonderful topics to be attached:

Asp. NET Control Usage Manual

Asp. NET data-bound controls using totals

Asp. NET controls use totals

The above is about the asp.net in the GridView control of a variety of uses, is very comprehensive, the goal is to let the pro play the GridView control, I hope you like the small compiled these two articles.

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.