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 <= 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 <= 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:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns=" http://www.w3.org/1999/xhtml "> <head runat=" Server "> <title>gridview Show hidden Columns </ title> </head> <body style= "font-size=12px" > <form id= "Form1" runat= "Server" > <div> <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" > <footerstyle Backcolor= "White" forecolor= "#000066"/> <Columns> <asp:boundfield datafield= "ID number" headertext= "number" readonly= "True"/> <asp:boundfield datafield= "name" headertext= "user name"/> <asp:boundfield DataField= "ZIP code" headertext= "Postal Code" sortexpression= "/> <asp:boundfield datafield=" Home Address " headertext= "Home Address"/> <asp:commandfield headertext= "select" showselectbutton= "True"/> <asp:commandfield headertext= "edit" showeditbutton= "true"/> <asp:commandfield headertext= "Delete" showdeletebutton= "true"/> </ columns> <rowstyle forecolor= "#000066"/> <selectedrowstyle backcolor= "True" font-bold= "#669999" forecolor= "White"/> <pagerstyle backcolor= ' white ' forecolor= ' #000066 ' horizontalalign= ' left '/> < HeaderStyle backcolor= "#006699" font-bold= "True" forecolor= "white"/> </asp:GridView> <asp:checkbox id= " CheckBox1 "runat=" Server "font-size=" 12px "oncheckedchanged=" checkbox1_checkedchanged "text=" Show hidden Home Address "/></ div> </form> </body> </html>
14.GridView pop-up new page/popup set size position new window:
Effect Chart:
Solution One: Simple method, new window not fixed size
<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" > <footerstyle Backcolor= "White" forecolor= "#000066"/> <Columns> <asp:boundfield datafield= "ID number" headertext= "number" readonly= "True"/> <asp:boundfield datafield= Postal Code "headertext=" Postal Code "sortexpression=/>: BoundField datafield= "Home Address" headertext= "Home Address"/> <asp:hyperlinkfield headertext= "name" text= "name" datanavigateurlfields= "name" datanavigateurlformatstring= "Default6.aspx?"
goodsid={0} "target=" mainframe "navigateurl=" ~/default6.aspx "datatextfield=" Name > </asp:HyperLinkField> <asp:commandfield headertext= "Select" showselectbutton= "True"/> <asp:commandfield headertext= "edit" showeditbutton= "True"/> <asp:commandfielD headertext= "Delete" showdeletebutton= "True"/> </Columns> <rowstyle forecolor= "#000066"/> < SelectedRowStyle backcolor= "#669999" font-bold= "True" forecolor= "white"/> <pagerstyle backcolor= "White" Forecolor= "#000066" horizontalalign= "left"/> <headerstyle backcolor= "#006699" font-bold= "True" forecolor= "
White "/> </asp:GridView>
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:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns=" http://www.w3.org/1999/xhtml "> <head runat=" Server "> <title>gridview fixed header </ Title> <style>.
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;} </style> </head> <body style= "font-size=12px" > <form id= "Form1" runat= "Server" > <div style= "overflow-y: scroll; height:200px;width:300px "id=" Dvbody "> <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"> <footerstyle backcolor= "White" forecolor= "#000066"/> <Columns> <asp:boundfield datafield= "ID card number" headertext= "number" readonly= "True"/> <asp:boundfield datafield= "headertext=" Postal Code "sortexpression=" Postal Code "/ > <asp:boundfield datafield= "Home Address" headertext= "Home Address"/> <asp:boundfield datafield= "name" headertext= "name"/ > </Columns> <rowstyle forecolor= "#000066"/> <selectedrowstyle backcolor= "#669999" font-bold= "True "Forecolor=" white "/> <pagerstyle backcolor=" white "forecolor=" #000066 "horizontalalign=" left "cssclass=" Ms-formlabel datagridfixedheader "/> <headerstyle backcolor=" "#006699" font-bold= "True" forecolor= "white"
cssclass= "Freezing"/> </asp:GridView> </div> </form> </body> </html>
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 </th></tr><tr>";
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 </th></tr><tr>";
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:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns=" http://www.w3.org/1999/xhtml "> <head runat=" Server "> <title>gridview merge Multiple header headers </title> </head> <body > <form id= "Form1" runat= "Server" > <div > <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" > <footerstyle backcolor= "White" Forecolor= "#000066"/> <Columns> <asp:commandfield headertext= edit showeditbutton= "True"/> <asp: BoundField datafield= "ID number" headertext= "number" readonly= "True"/> <asp:boundfield "name" datafield= "name"/ > <asp:boundfield datafield= "Birth date" headertext= "Postal code"/> <asp:boundfiEld datafield= "Starting salary" headertext= "starting salary"/> <asp:boundfield datafield= "Home Address" headertext= "Home Address"/> <asp: BoundField datafield= "headertext=" Postal code "/> </Columns> <rowstyle forecolor=" #000066 "/> < SelectedRowStyle backcolor= "#669999" font-bold= "True" forecolor= "white"/> <pagerstyle backcolor= "White" Forecolor= "#000066" horizontalalign= "left" cssclass= "Ms-formlabel datagridfixedheader"/> <headerstyle Backcolor= "#006699" font-bold= "True" forecolor= "white"/> </asp:GridView> </div> </form> </ Body> </html>
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 <= 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 ();
}
}
Foreground code:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns=" http://www.w3.org/1999/xhtml "> <head id=" Head1 "runat=" Server "> <title> The GridView highlights a cell clear moon http://blog.csdn.net/21aspnet </title> </head> <body > <form id= "Form1" runat= "Server" > <div > <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" > <footerstyle Backcolor= "White" forecolor= "#000066"/> <Columns> <asp:commandfield headertext= "edit" showeditbutton= " True "/> <asp:boundfield datafield=" ID number "headertext=" number "readonly=" true "/> <asp:boundfield DataField=" Name "headertext=" name "/> <asp:boundfield datafield=" date of birth headertext= "zip code"/> <Asp:boundfield datafield= "Starting salary" headertext= "Starting salary" dataformatstring= "{0:c}" htmlencode= "false"/>
datafield= "Home Address" headertext= "Home Address"/> <asp:boundfield datafield= "headertext=" Postal code "/> </Columns> <rowstyle forecolor= "#000066"/> <selectedrowstyle backcolor= "#669999" font-bold= "True" forecolor= "white"/ > <pagerstyle backcolor= "White" forecolor= "the #000066" horizontalalign= "left" cssclass= "Ms-formlabel Datagridfixedheader "/> <headerstyle backcolor=" #006699 "font-bold=" True "forecolor=" white "/> </asp:
gridview> </div> </form> </body> </html>
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 >= 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!
<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" > <footerstyle backcolor= "White" forecolor= "#000066"/> <Columns> <asp:commandfield headertext= "edit" Showeditbutton= "true"/> <asp:boundfield datafield= "ID number" headertext= "number" readonly= "true"/> <asp: BoundField datafield= "name" headertext= "name"/> <asp:boundfield datafield= "Birth date" headertext= "Zip Code"/>: BoundField datafield= "Home Address" headertext= "Home Address"/> <asp:boundfield datafield= "Postal code" headertext= < Asp:boundfield datafield= "Starting salary" headertext= "starting salary"/> </Columns> <rowstyle forecolor= "#000066"/> < SelectedRowStyle backcolor= "#669999" font-bold= "True" forecolor= "white"/> <pagersTyle backcolor= "White" forecolor= "the #000066" horizontalalign= "left" cssclass= "Ms-formlabel datagridfixedheader"/>
<headerstyle backcolor= "#006699" font-bold= "True" forecolor= "white"/> </asp:GridView>
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:
<asp:gridview id= "GridView1" runat= "Server" cellpadding= "3" backcolor= "white" bordercolor= "#CCCCCC" borderstyle= " None "borderwidth=" 1px "font-size=" 12px "> <footerstyle backcolor=" White "forecolor=" #000066 "/> <columns > <asp:boundfield datafield= "ID number" headertext= "number" readonly= "True"/> <asp:boundfield "name" headertext= "name"/> <asp:boundfield datafield= "Birth date" headertext= "Postal code"/> <asp:boundfield DataField= "Home Address" headertext= "Home Address"/> <asp:boundfield datafield= "headertext=" Postal code "/> <asp:boundfield DataField=" Starting salary " headertext= "Starting salary"/> </Columns> <rowstyle forecolor= "#000066/> <selectedrowstyle backcolor=" #669999 "Font-bold=" True "forecolor=" white "/> <pagerstyle backcolor=" white "forecolor=" #000066 "horizontalalign=" left "Cssclass=" Ms-formlabel datagridfixedheader "/> <headerstyle backcolor=" #006699 "font-bold=" True "ForeColor=" White "/> </asp:GridView> <asp:button id=" Button1 "Run"at= "Server" onclick= "Button1_Click" text= "Export"/>
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.