GridView 72绝技

来源:互联网 发布:淘宝刷钻石 编辑:程序博客网 时间:2024/06/07 11:53

文章转自:http://blog.csdn.net/21aspnet/article/details/1540301

http://blog.csdn.net/diyoosjtu/article/details/8090160


GridView无代码分页排序

效果图:


1.AllowSorting设为True,aspx代码中是AllowSorting="True";
2.默认1页10条,如果要修改每页条数,修改PageSize即可,在aspx代码中是PageSize="12"。
3.默认的是单向排序的,右击GridView弹出“属性”,选择AllowSorting为True即可。

GridView选中,编辑,取消,删除

效果图:

后台代码:
你可以使用sqlhelper,本文没用。代码如下:

[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Data.SqlClient;  
  11. public partial class _Default : System.Web.UI.Page   
  12. {  
  13. //清清月儿http://blog.csdn.net/21aspnet    
  14.     SqlConnection sqlcon;  
  15.     SqlCommand sqlcom;  
  16.     string strCon = "Data Source=(local);Database=数据库名;Uid=帐号;Pwd=密码";  
  17.     protected void Page_Load(object sender, EventArgs e)  
  18.     {  
  19.         if (!IsPostBack)  
  20.         {  
  21.             bind();  
  22.         }  
  23.     }  
  24.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  25.     {  
  26.         GridView1.EditIndex = e.NewEditIndex;  
  27.         bind();  
  28.     }  
  29. //删除   
  30.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  31.     {  
  32.         string sqlstr = "delete from 表 where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  33.         sqlcon = new SqlConnection(strCon);  
  34.         sqlcom = new SqlCommand(sqlstr,sqlcon);  
  35.         sqlcon.Open();  
  36.         sqlcom.ExecuteNonQuery();  
  37.         sqlcon.Close();  
  38.         bind();  
  39.     }  
  40. //更新   
  41.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  42.     {  
  43.         sqlcon = new SqlConnection(strCon);  
  44.         string sqlstr = "update 表 set 字段1='"  
  45.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',字段2='"  
  46.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',字段3='"  
  47.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where id='"   
  48.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  49.         sqlcom=new SqlCommand(sqlstr,sqlcon);  
  50.         sqlcon.Open();  
  51.         sqlcom.ExecuteNonQuery();  
  52.         sqlcon.Close();  
  53.         GridView1.EditIndex = -1;  
  54.         bind();  
  55.     }  
  56. //取消   
  57.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  58.     {  
  59.         GridView1.EditIndex = -1;  
  60.         bind();  
  61.     }  
  62. //绑定   
  63.     public void bind()  
  64.     {  
  65.         string sqlstr = "select * from 表";  
  66.         sqlcon = new SqlConnection(strCon);  
  67.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  68.         DataSet myds = new DataSet();  
  69.         sqlcon.Open();  
  70.         myda.Fill(myds, "表");  
  71.         GridView1.DataSource = myds;  
  72.         GridView1.DataKeyNames = new string[] { "id" };//主键  
  73.         GridView1.DataBind();  
  74.         sqlcon.Close();  
  75.     }  
  76. }  
前台主要代码:
[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"  
  2.               ForeColor="#333333" GridLines="None" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"  
  3.                OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit">  
  4.                <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />  
  5.                <Columns>  
  6.                             <asp:BoundField DataField="身份证号码" HeaderText="用户ID" ReadOnly="True" />  
  7.                             <asp:BoundField DataField="姓名" HeaderText="用户姓名" />  
  8.                             <asp:BoundField DataField="员工性别" HeaderText="性别" />  
  9.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" />  
  10.                             <asp:CommandField HeaderText="选择" ShowSelectButton="True" />  
  11.                             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />  
  12.                             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />  
  13.               </Columns>  
  14.                         <RowStyle ForeColor="#000066" />  
  15.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  16.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  17.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  18.                     </asp:GridView>  

GridView正反双向排序

效果图:点姓名各2次的排序,点其他也一样可以。

后台代码:

[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Collections;  
  5. using System.Web;  
  6. using System.Web.Security;  
  7. using System.Web.UI;  
  8. using System.Web.UI.WebControls;  
  9. using System.Web.UI.WebControls.WebParts;  
  10. using System.Web.UI.HtmlControls;  
  11. using System.Data.SqlClient;  
  12. public partial class Default3 : System.Web.UI.Page  
  13. {  
  14. //清清月儿的博客http://blog.csdn.net/21aspnet    
  15.     SqlConnection sqlcon;  
  16.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=";  
  17.     protected void Page_Load(object sender, EventArgs e)  
  18.     {  
  19.         if (!IsPostBack)  
  20.         {  
  21.             ViewState["SortOrder"] = "身份证号码";  
  22.             ViewState["OrderDire"] = "ASC";  
  23.             bind();  
  24.         }  
  25.     }  
  26.     protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)  
  27.     {  
  28.         string sPage = e.SortExpression;  
  29.         if (ViewState["SortOrder"].ToString() == sPage)  
  30.         {  
  31.             if (ViewState["OrderDire"].ToString() == "Desc")  
  32.                 ViewState["OrderDire"] = "ASC";  
  33.             else  
  34.                 ViewState["OrderDire"] = "Desc";  
  35.         }  
  36.         else  
  37.         {  
  38.             ViewState["SortOrder"] = e.SortExpression;  
  39.         }  
  40.         bind();  
  41.     }  
  42.     public void bind()  
  43.     {  
  44.           
  45.         string sqlstr = "select top 5 * from 飞狐工作室";  
  46.         sqlcon = new SqlConnection(strCon);  
  47.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  48.         DataSet myds = new DataSet();  
  49.         sqlcon.Open();  
  50.         myda.Fill(myds, "飞狐工作室");  
  51.         DataView view = myds.Tables["飞狐工作室"].DefaultView;  
  52.         string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];  
  53.         view.Sort = sort;  
  54.         GridView1.DataSource = view;  
  55.         GridView1.DataBind();  
  56.         sqlcon.Close();  
  57.     }  
  58. }  
前台主要代码:
[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"  
  2.                         CellPadding="3" Font-Size="9pt" OnSorting="GridView1_Sorting" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">  
  3.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  4.                         <Columns>  
  5.                              <asp:BoundField DataField="身份证号码" HeaderText="用户ID" SortExpression="身份证号码" />  
  6.                             <asp:BoundField DataField="姓名" HeaderText="用户姓名" SortExpression="姓名"/>  
  7.                             <asp:BoundField DataField="员工性别" HeaderText="性别" SortExpression="员工性别"/>  
  8.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址"/>  
  9.                                   
  10.                         </Columns>  
  11.                         <RowStyle ForeColor="#000066" />  
  12.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  13.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  14.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  15.                     </asp:GridView>  

GridView和下拉菜单DropDownList结合

效果图:

后台代码:

[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Collections;  
  5. using System.Web;  
  6. using System.Web.Security;  
  7. using System.Web.UI;  
  8. using System.Web.UI.WebControls;  
  9. using System.Web.UI.WebControls.WebParts;  
  10. using System.Web.UI.HtmlControls;  
  11. using System.Data.SqlClient;  
  12. public partial class Default4 : System.Web.UI.Page  
  13. {  
  14.     SqlConnection sqlcon;  
  15.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.         DropDownList ddl;  
  19.         if (!IsPostBack)  
  20.         {  
  21.             string sqlstr = "select top 5 * from 飞狐工作室";  
  22.             sqlcon = new SqlConnection(strCon);  
  23.             SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  24.             DataSet myds = new DataSet();  
  25.             sqlcon.Open();  
  26.             myda.Fill(myds, "飞狐工作室");  
  27.             GridView1.DataSource = myds;  
  28.             GridView1.DataBind();  
  29.             for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  30.             {  
  31.                 DataRowView mydrv = myds.Tables["飞狐工作室"].DefaultView[i];  
  32.                 if (Convert.ToString(mydrv["员工性别"]).Trim() == "True")  
  33.                 {  
  34.                     ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");  
  35.                     ddl.SelectedIndex = 0;  
  36.                 }  
  37.                 if (Convert.ToString(mydrv["员工性别"]).Trim() == "False")  
  38.                 {  
  39.                     ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");  
  40.                     ddl.SelectedIndex = 1;  
  41.                 }  
  42.             }  
  43.             sqlcon.Close();  
  44.         }  
  45.     }  
  46.     public SqlDataReader ddlbind()  
  47.     {  
  48.         string sqlstr = "select distinct 员工性别 from 飞狐工作室";  
  49.         sqlcon = new SqlConnection(strCon);  
  50.         SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);  
  51.         sqlcon.Open();  
  52.         return sqlcom.ExecuteReader();  
  53.     }  
前台主要代码:
[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"  
  2.                         CellPadding="3" Font-Size="9pt"  BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">  
  3.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  4.                         <Columns>  
  5.                              <asp:BoundField DataField="身份证号码" HeaderText="用户ID" SortExpression="身份证号码" />  
  6.                             <asp:BoundField DataField="姓名" HeaderText="用户姓名" SortExpression="姓名"/>  
  7.                             <asp:TemplateField HeaderText="员工性别">  
  8.                                 <ItemTemplate>  
  9.                                     <asp:DropDownList ID="DropDownList1" runat="server" DataSource='<%# ddlbind()%>' DataValueField="员工性别" DataTextField="员工性别">  
  10.                                     </asp:DropDownList>  
  11.                                 </ItemTemplate>  
  12.                             </asp:TemplateField>  
  13.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址"/>  
  14.                                   
  15.                         </Columns>  
  16.                         <RowStyle ForeColor="#000066" />  
  17.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  18.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  19.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  20.                     </asp:GridView>  

GridView和CheckBox结合

效果图:

后台代码:

[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Data.SqlClient;  
  11. public partial class Default5 : System.Web.UI.Page  
  12. {  
  13. //清清月儿http://blog.csdn.net/21aspnet    
  14.     SqlConnection sqlcon;  
  15.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.         if (!IsPostBack)  
  19.         {  
  20.             bind();  
  21.         }  
  22.     }  
  23.     protected void CheckBox2_CheckedChanged(object sender, EventArgs e)  
  24.     {  
  25.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  26.         {  
  27.             CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");  
  28.             if (CheckBox2.Checked == true)  
  29.             {  
  30.                 cbox.Checked = true;  
  31.             }  
  32.             else  
  33.             {  
  34.                 cbox.Checked = false;  
  35.             }  
  36.         }  
  37.     }  
  38.     protected void Button2_Click(object sender, EventArgs e)  
  39.     {  
  40.         sqlcon = new SqlConnection(strCon);  
  41.         SqlCommand sqlcom;  
  42.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  43.         {  
  44.             CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");  
  45.             if (cbox.Checked == true)  
  46.             {  
  47.                 string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[i].Value + "'";  
  48.                 sqlcom = new SqlCommand(sqlstr, sqlcon);  
  49.                 sqlcon.Open();  
  50.                 sqlcom.ExecuteNonQuery();  
  51.                 sqlcon.Close();  
  52.             }  
  53.         }  
  54.         bind();  
  55.     }  
  56.     protected void Button1_Click(object sender, EventArgs e)  
  57.     {  
  58.         CheckBox2.Checked = false;  
  59.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  60.         {  
  61.             CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");  
  62.             cbox.Checked = false;  
  63.         }  
  64.     }  
  65.     public void bind()  
  66.     {  
  67.         string sqlstr = "select top 5 * from 飞狐工作室";  
  68.         sqlcon = new SqlConnection(strCon);  
  69.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  70.         DataSet myds = new DataSet();  
  71.         sqlcon.Open();  
  72.         myda.Fill(myds, "tb_Member");  
  73.         GridView1.DataSource = myds;  
  74.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  75.         GridView1.DataBind();  
  76.         sqlcon.Close();  
  77.     }  
  78. }  
前台主要代码:
[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"  
  2.                         CellPadding="3" Font-Size="9pt"  BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">  
  3.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  4.                         <Columns>  
  5.                              <asp:TemplateField>  
  6.                                 <ItemTemplate>  
  7.                                     <asp:CheckBox ID="CheckBox1" runat="server" />  
  8.                                 </ItemTemplate>  
  9.                             </asp:TemplateField>  
  10.                              <asp:BoundField DataField="身份证号码" HeaderText="用户ID" SortExpression="身份证号码" />  
  11.                             <asp:BoundField DataField="姓名" HeaderText="用户姓名" SortExpression="姓名"/>  
  12.                               
  13.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址"/>  
  14.                                   
  15.                         </Columns>  
  16.                         <RowStyle ForeColor="#000066" />  
  17.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  18.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  19.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  20.                     </asp:GridView>  
  21.                      <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" Font-Size="9pt" OnCheckedChanged="CheckBox2_CheckedChanged"  
  22.                         Text="全选" />  
  23.                     <asp:Button ID="Button1" runat="server" Font-Size="9pt" Text="取消" OnClick="Button1_Click" />  
  24.                     <asp:Button ID="Button2" runat="server" Font-Size="9pt" Text="删除" OnClick="Button2_Click" />  

鼠标移到GridView某一行时改变该行的背景色方法一

效果图:

做法:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:

[csharp] view plaincopyprint?
  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.     {  
  3.         int i;  
  4.         //执行循环,保证每条数据都可以更新   
  5.         for (i = 0; i < GridView1.Rows.Count; i++)  
  6.         {  
  7.             //首先判断是否是数据行   
  8.             if (e.Row.RowType == DataControlRowType.DataRow)  
  9.             {  
  10.                 //当鼠标停留时更改背景色   
  11.                 e.Row.Attributes.Add("onmouseover""c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");  
  12.                 //当鼠标移开时还原背景色   
  13.                 e.Row.Attributes.Add("onmouseout""this.style.backgroundColor=c");  
  14.             }  
  15.         }  
  16.     }  
前台代码:
[html] view plaincopyprint?
  1. <html xmlns="http://www.w3.org/1999/xhtml" >  
  2. <head runat="server">  
  3.     <title>实现鼠标划过改变GridView的行背景色 清清月儿http://blog.csdn.net/21aspnet </title>  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.     <div>  
  8.         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="身份证号码"  
  9.             DataSourceID="SqlDataSource1" AllowSorting="True" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound">  
  10.             <Columns>  
  11.                 <asp:BoundField DataField="身份证号码" HeaderText="身份证号码" ReadOnly="True" SortExpression="身份证号码" />  
  12.                 <asp:BoundField DataField="姓名" HeaderText="姓名" SortExpression="姓名" />  
  13.                 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址" />  
  14.                 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" />  
  15.             </Columns>  
  16.             <FooterStyle BackColor="White" ForeColor="#000066" />  
  17.             <RowStyle ForeColor="#000066" />  
  18.             <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  19.             <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  20.             <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  21.         </asp:GridView>  
  22.         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:北风贸易ConnectionString1 %>"  
  23.             SelectCommand="SELECT top 5 [身份证号码], [姓名], [员工性别], [家庭住址], [邮政编码] FROM [飞狐工作室]" DataSourceMode="DataReader"></asp:SqlDataSource>  
  24.       
  25.     </div>  
  26.     </form>  
  27. </body>  
  28. </html>  

鼠标移到GridView某一行时改变该行的背景色方法二

效果图:

做法:和上面的一样就是代码不同

[csharp] view plaincopyprint?
  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.     {  
  3.         //int i;   
  4.         ////执行循环,保证每条数据都可以更新   
  5.         //for (i = 0; i < GridView1.Rows.Count; i++)  
  6.         //{   
  7.         //    //首先判断是否是数据行   
  8.         //    if (e.Row.RowType == DataControlRowType.DataRow)  
  9.         //    {   
  10.         //        //当鼠标停留时更改背景色   
  11.         //        e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");  
  12.         //        //当鼠标移开时还原背景色   
  13.         //        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");  
  14.         //    }   
  15.         //}   
  16.         //如果是绑定数据行    
  17.         if (e.Row.RowType == DataControlRowType.DataRow)  
  18.         {  
  19.             //鼠标经过时,行背景色变    
  20.             e.Row.Attributes.Add("onmouseover""this.style.backgroundColor='#E6F5FA'");  
  21.             //鼠标移出时,行背景色变    
  22.             e.Row.Attributes.Add("onmouseout""this.style.backgroundColor='#FFFFFF'");  
  23.         }  
  24.     }  

GridView实现删除时弹出确认对话框

效果图:

实现方法:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:

[csharp] view plaincopyprint?
  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.     {  
  3.         //如果是绑定数据行    
  4.         if (e.Row.RowType == DataControlRowType.DataRow)  
  5.         {  
  6.              if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)  
  7.             {  
  8.                 ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick""javascript:return confirm('你确认要删除:/"" + e.Row.Cells[1].Text + "/"吗?')");  
  9.             }  
  10.         }  
  11.     }  

GridView实现自动编号

效果图:

实现方法:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:

[csharp] view plaincopyprint?
  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.     {  
  3.         //如果是绑定数据行 //清清月儿http://blog.csdn.net/21aspnet   
  4.         if (e.Row.RowType == DataControlRowType.DataRow)  
  5.         {  
  6.             ////鼠标经过时,行背景色变    
  7.             //e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");  
  8.             ////鼠标移出时,行背景色变    
  9.             //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");  
  10.             ////当有编辑列时,避免出错,要加的RowState判断    
  11.             //if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)  
  12.             //{   
  13.             //    ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:/"" + e.Row.Cells[1].Text + "/"吗?')");  
  14.             //}   
  15.         }  
  16.         if (e.Row.RowIndex != -1)  
  17.         {  
  18.             int id = e.Row.RowIndex + 1;  
  19.             e.Row.Cells[0].Text = id.ToString();  
  20.         }  
  21.     }  
注意这时最好把前台的第一列的表头该为“编号”,因为以前的第一列被“吃掉”了。
[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"  
  2.                         OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound">  
  3.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  4.                         <Columns>  
  5.                             <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  6.                             <asp:BoundField DataField="姓名" HeaderText="用户姓名" />  
  7.                             <asp:BoundField DataField="员工性别" HeaderText="性别" />  
  8.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" />  
  9.                             <asp:CommandField HeaderText="选择" ShowSelectButton="True" />  
  10.                             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />  
  11.                             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />  
  12.                         </Columns>  
  13.                         <RowStyle ForeColor="#000066" />  
  14.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  15.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  16.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  17.                     </asp:GridView>  

GridView实现自定义时间货币等字符串格式

效果图:
图1-未格式化前

图2-格式化后

解决方法:

在asp.net 2.0中,如果要在绑定列中显示比如日期格式等,如果用下面的方法是显示不了的

[html] view plaincopyprint?
  1. <asp :BoundField DataField="CreationDate"   
  2. DataFormatString="{0:M-dd-yyyy}"   
  3. HeaderText="CreationDate" />  

主要是由于htmlencode属性默认设置为true,已防止XSS攻击,安全起见而用的,所以,可以有以下两种方法解决

1、

[html] view plaincopyprint?
  1. <asp :GridView ID="GridView1" runat="server">  
  2. <columns>  
  3. <asp :BoundField DataField="CreationDate"   
  4. DataFormatString="{0:M-dd-yyyy}"   
  5. HtmlEncode="false"  
  6. HeaderText="CreationDate" />  
  7. </columns>  
  8. </asp>  

将htmlencode设置为false即可

另外的解决方法为,使用模版列

[html] view plaincopyprint?
  1. <asp :GridView ID="GridView3" runat="server" >  
  2. <columns>  
  3. <asp :TemplateField HeaderText="CreationDate" >  
  4. <edititemtemplate>  
  5. <asp :Label ID="Label1" runat="server"   
  6. Text='<%# Eval("CreationDate", "{0:M-dd-yyyy}") %>'>  
  7. </asp>  
  8. </edititemtemplate>  
  9. <itemtemplate>  
  10. <asp :Label ID="Label1" runat="server"   
  11. Text=’<%# Bind("CreationDate", "{0:M-dd-yyyy}") %>'>  
  12. </asp>  
  13. </itemtemplate>  
  14. </asp>  
  15. </columns>  
  16. </asp>  
前台代码:
[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="身份证号码"  
  2.             DataSourceID="SqlDataSource1" AllowSorting="True" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound">  
  3.             <Columns>  
  4.                 <asp:BoundField DataField="身份证号码" HeaderText="身份证号码" ReadOnly="True" SortExpression="身份证号码" />  
  5.                 <asp:BoundField DataField="姓名" HeaderText="姓名" SortExpression="姓名" />  
  6.                 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" />  
  7.                 <asp:BoundField DataField="出生日期" HeaderText="出生日期" SortExpression="出生日期" />  
  8.                 <asp:BoundField DataField="起薪" HeaderText="起薪" SortExpression="起薪" />  
  9.             </Columns>  
  10.             <FooterStyle BackColor="White" ForeColor="#000066" />  
  11.             <RowStyle ForeColor="#000066" />  
  12.             <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  13.             <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  14.             <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  15.         </asp:GridView>  
  16.         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:北风贸易ConnectionString1 %>"  
  17.             SelectCommand="SELECT top 5 [出生日期], [起薪], [身份证号码], [姓名], [家庭住址], [邮政编码] FROM [飞狐工作室]" DataSourceMode="DataReader"></asp:SqlDataSource>  
附录-常用格式化公式:
{0:C}  货币;
{0:D4}由0填充的4个字符宽的字段中显示整数;
{0:000.0}四舍五入小数点保留第几位有效数字;
{0:N2}小数点保留2位有效数字;{0:N2}%   小数点保留2位有效数字加百分号;
{0:D}长日期;{0:d}短日期;{0:yy-MM-dd}   例如07-3-25;;{0:yyyy-MM-dd}  例如2007-3-25

GridView实现用“...”代替超长字符串

效果图:

解决方法:数据绑定后过滤每一行即可

[csharp] view plaincopyprint?
  1. for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  2.         {  
  3.             DataRowView mydrv;  
  4.             string gIntro;  
  5.             if (GridView1.PageIndex == 0)  
  6.             {  
  7.                 mydrv = myds.Tables["飞狐工作室"].DefaultView[i];//表名  
  8.                 gIntro = Convert.ToString(mydrv["家庭住址"]);//所要处理的字段  
  9.                 GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);  
  10.             }  
  11.             else  
  12.             {  
  13.                 mydrv = myds.Tables["飞狐工作室"].DefaultView[i + (5 * GridView1.PageIndex)];  
  14.                 gIntro = Convert.ToString(mydrv["家庭住址"]);  
  15.                 GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);  
  16.             }  
  17.         }   
调用的方法:
[csharp] view plaincopyprint?
  1. public string SubStr(string sString, int nLeng)  
  2.    {  
  3.        if (sString.Length <= nLeng)  
  4.        {  
  5.            return sString;  
  6.        }  
  7.        string sNewStr = sString.Substring(0, nLeng);  
  8.        sNewStr = sNewStr + "...";  
  9.        return sNewStr;  
  10.    }  
后台全部代码:
[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Data.SqlClient;  
  11. public partial class _Default : System.Web.UI.Page   
  12. {  
  13.     SqlConnection sqlcon;  
  14.     SqlCommand sqlcom;  
  15.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.         if (!IsPostBack)  
  19.         {  
  20.             ViewState["SortOrder"] = "身份证号码";  
  21.             ViewState["OrderDire"] = "ASC";  
  22.             bind();  
  23.         }  
  24.     }  
  25.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  26.     {  
  27.         GridView1.EditIndex = e.NewEditIndex;  
  28.         bind();  
  29.     }  
  30.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  31.     {  
  32.         string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  33.         sqlcon = new SqlConnection(strCon);  
  34.         sqlcom = new SqlCommand(sqlstr,sqlcon);  
  35.         sqlcon.Open();  
  36.         sqlcom.ExecuteNonQuery();  
  37.         sqlcon.Close();  
  38.         bind();  
  39.     }  
  40.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  41.     {  
  42.         sqlcon = new SqlConnection(strCon);  
  43.         string sqlstr = "update 飞狐工作室 set 姓名='"  
  44.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"  
  45.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"   
  46.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  47.         sqlcom=new SqlCommand(sqlstr,sqlcon);  
  48.         sqlcon.Open();  
  49.         sqlcom.ExecuteNonQuery();  
  50.         sqlcon.Close();  
  51.         GridView1.EditIndex = -1;  
  52.         bind();  
  53.     }  
  54.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  55.     {  
  56.         GridView1.EditIndex = -1;  
  57.         bind();  
  58.     }  
  59.     public void bind()  
  60.     {  
  61.         string sqlstr = "select top 5 * from 飞狐工作室";  
  62.         sqlcon = new SqlConnection(strCon);  
  63.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  64.         DataSet myds = new DataSet();  
  65.         sqlcon.Open();  
  66.         myda.Fill(myds, "飞狐工作室");  
  67.         GridView1.DataSource = myds;  
  68.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  69.         GridView1.DataBind();  
  70.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  71.         {  
  72.             DataRowView mydrv;  
  73.             string gIntro;  
  74.             if (GridView1.PageIndex == 0)  
  75.             {  
  76.                 mydrv = myds.Tables["飞狐工作室"].DefaultView[i];  
  77.                 gIntro = Convert.ToString(mydrv["家庭住址"]);  
  78.                 GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);  
  79.             }  
  80.             else  
  81.             {  
  82.                 mydrv = myds.Tables["飞狐工作室"].DefaultView[i + (5 * GridView1.PageIndex)];  
  83.                 gIntro = Convert.ToString(mydrv["家庭住址"]);  
  84.                 GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);  
  85.             }  
  86.         }  
  87.           
  88.         sqlcon.Close();  
  89.     }  
  90.     public string SubStr(string sString, int nLeng)  
  91.     {  
  92.         if (sString.Length <= nLeng)  
  93.         {  
  94.             return sString;  
  95.         }  
  96.         string sNewStr = sString.Substring(0, nLeng);  
  97.         sNewStr = sNewStr + "...";  
  98.         return sNewStr;  
  99.     }  
  100.     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  101.     {  
  102.         //如果是绑定数据行    
  103.         if (e.Row.RowType == DataControlRowType.DataRow)  
  104.         {  
  105.             ////鼠标经过时,行背景色变    
  106.             //e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");  
  107.             ////鼠标移出时,行背景色变    
  108.             //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");  
  109.             ////当有编辑列时,避免出错,要加的RowState判断    
  110.             //if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)  
  111.             //{   
  112.             //    ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:/"" + e.Row.Cells[1].Text + "/"吗?')");  
  113.             //}   
  114.         }  
  115.         if (e.Row.RowIndex != -1)  
  116.         {  
  117.             int id = e.Row.RowIndex + 1;  
  118.             e.Row.Cells[0].Text = id.ToString();  
  119.         }  
  120.     }  
  121. }  

GridView一般换行与强制换行

效果图:

首先设置<asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  ItemStyle-Width="100" />
gridview里有一列绑定的数据很长,显示的时候在一行里面显示,页面拉得很宽。
原因是连续英文段为一个整体导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add("word-break", "break-all")就可以。

如果要给所有的列增加此属性:

[csharp] view plaincopyprint?
  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         //正常换行   
  4.         GridView1.Attributes.Add("style""word-break:keep-all;word-wrap:normal");  
  5.         //下面这行是自动换行   
  6.         GridView1.Attributes.Add("style""word-break:break-all;word-wrap:break-word");  
  7.         if (!IsPostBack)  
  8.         {  
  9.              bind();//调用数据绑定即可   
  10.         }  
  11.     }  
总之:善用CSS的word-break:break-all;word-wrap:break-word属性即可,这个属性是通用的对于顽固的南换行问题都可以解决,不局限于GridView。

GridView显示隐藏某一列

本方案为月儿独创,不同于网上其他方式,我觉得用一个CheckBox更人性化,这样可以隐藏不必要的列,让用户自己选择需要出现的列,在处理多列时这是一个很好的解决方案!

效果图:
图1-开始

图2-点击显示的CheckBox后

解决方案:

[csharp] view plaincopyprint?
  1. public void bind()  
  2.     {  
  3.         string sqlstr = "select top 5 * from 飞狐工作室";  
  4.         sqlcon = new SqlConnection(strCon);  
  5.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  6.         DataSet myds = new DataSet();  
  7.         sqlcon.Open();  
  8.         myda.Fill(myds, "飞狐工作室");  
  9.         GridView1.DataSource = myds;  
  10.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  11.         GridView1.DataBind();  
  12.         sqlcon.Close();  
  13.         GridView1.Columns[3].Visible = false;//一开始隐藏  
  14.         CheckBox1.Checked = false;//如果不这样后面的代码会把他True  
  15.     }  
双击CheckBox1,在CheckedChanged方法里写上代码,最后代码如下:
[csharp] view plaincopyprint?
  1. protected void CheckBox1_CheckedChanged(object sender, EventArgs e)  
  2.     {  
  3.          GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible;  
  4.          Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString());  
  5.     }  

注意:CheckBox1的AutoPostBack要True

后台全部代码如下:

[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Data.SqlClient;  
  11. public partial class _Default : System.Web.UI.Page   
  12. {  
  13.     SqlConnection sqlcon;  
  14.     SqlCommand sqlcom;   
  15.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.         if (!IsPostBack)  
  19.         {  
  20.             ViewState["SortOrder"] = "身份证号码";  
  21.             ViewState["OrderDire"] = "ASC";  
  22.             bind();  
  23.                    }  
  24.     }  
  25.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  26.     {  
  27.         GridView1.EditIndex = e.NewEditIndex;  
  28.         bind();  
  29.     }  
  30.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  31.     {  
  32.         string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  33.         sqlcon = new SqlConnection(strCon);  
  34.         sqlcom = new SqlCommand(sqlstr,sqlcon);  
  35.         sqlcon.Open();  
  36.         sqlcom.ExecuteNonQuery();  
  37.         sqlcon.Close();  
  38.         bind();  
  39.     }  
  40.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  41.     {  
  42.         sqlcon = new SqlConnection(strCon);  
  43.         string sqlstr = "update 飞狐工作室 set 姓名='"  
  44.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"  
  45.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"   
  46.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  47.         sqlcom=new SqlCommand(sqlstr,sqlcon);  
  48.         sqlcon.Open();  
  49.         sqlcom.ExecuteNonQuery();  
  50.         sqlcon.Close();  
  51.         GridView1.EditIndex = -1;  
  52.         bind();  
  53.     }  
  54.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  55.     {  
  56.         GridView1.EditIndex = -1;  
  57.         bind();  
  58.     }  
  59.     public void bind()  
  60.     {  
  61.         string sqlstr = "select top 5 * from 飞狐工作室";  
  62.         sqlcon = new SqlConnection(strCon);  
  63.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  64.         DataSet myds = new DataSet();  
  65.         sqlcon.Open();  
  66.         myda.Fill(myds, "飞狐工作室");  
  67.         GridView1.DataSource = myds;  
  68.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  69.         GridView1.DataBind();  
  70.         sqlcon.Close();  
  71.         GridView1.Columns[3].Visible = false;  
  72.         CheckBox1.Checked = false;  
  73.     }  
  74.     protected void CheckBox1_CheckedChanged(object sender, EventArgs e)  
  75.     {  
  76.          GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible;  
  77.          Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString());  
  78.     }  
  79. }  
前台代码:
[html] view plaincopyprint?
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" >  
  3. <head runat="server">  
  4.     <title>GridView显示隐藏列 清清月儿http://blog.csdn.net/21aspnet </title>  
  5. </head>  
  6. <body style="font-size=12px">  
  7.     <form id="form1" runat="server">  
  8.     <div>  
  9.                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"  
  10.                         OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px"  >  
  11.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  12.                         <Columns>  
  13.                             <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  14.                             <asp:BoundField DataField="姓名" HeaderText="用户姓名" />  
  15.                             <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" />  
  16.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  />  
  17.                             <asp:CommandField HeaderText="选择" ShowSelectButton="True" />  
  18.                             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />  
  19.                             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />  
  20.                         </Columns>  
  21.                         <RowStyle ForeColor="#000066" />  
  22.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  23.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  24.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  25.                     </asp:GridView>  
  26.         <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" Font-Size="12px"  
  27.             OnCheckedChanged="CheckBox1_CheckedChanged" Text="显示隐藏家庭住址" /></div>  
  28.     </form>  
  29. </body>  
  30. </html>  

GridView弹出新页面/弹出新窗口

效果图:

方案一:简单的方法,新窗口不固定大小

[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"  
  2.                        OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px"  >  
  3.                        <FooterStyle BackColor="White" ForeColor="#000066" />  
  4.                        <Columns>  
  5.                            <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  6.                            <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" />  
  7.                            <asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  />  
  8.                            <asp:HyperLinkField HeaderText="姓名" Text="姓名" DataNavigateUrlFields="姓名" DataNavigateUrlFormatString="Default6.aspx?GoodsID={0}" Target="mainframe" NavigateUrl="~/Default6.aspx" DataTextField="姓名" >  
  9.                    </asp:HyperLinkField>  
  10.                            <asp:CommandField HeaderText="选择" ShowSelectButton="True" />  
  11.                            <asp:CommandField HeaderText="编辑" ShowEditButton="True" />  
  12.                            <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />  
  13.                        </Columns>  
  14.                        <RowStyle ForeColor="#000066" />  
  15.                        <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  16.                        <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  17.                        <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  18.                    </asp:GridView>  

DataNavigateUrlFields是链接的字段名,DataNavigateUrlFormatString是路径。

方案二:精确控制弹出窗口大小位置

[html] view plaincopyprint?
  1. <asp:HyperLinkColumn DataNavigateUrlField="EmployeeID" DataNavigateUrlFormatString="javascript:varwin=window.open('detail.aspx?ID={0}',null,'width=300,height=200');window.Close();"  
  2.        DataTextField="LastName" HeaderText="LastName"></asp:HyperLinkColumn>  
使用的是结合javascript的window.open方法,关于window.open的参数网上有很多帖子,本站也有许多参考
弹出窗口大全 http://blog.csdn.net/21aspnet/archive/2004/10/25/150231.aspx   即可!

GridView固定表头(不用javascript只用CSS,2行代码,很好用)

效果图:

代码:

[html] view plaincopyprint?
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" >  
  3. <head runat="server">  
  4.     <title>GridView固定表头 清清月儿http://blog.csdn.net/21aspnet </title>  
  5.         <style>   
  6. .Freezing   
  7.    {   
  8.       
  9.    position:relative ;   
  10.    table-layout:fixed;  
  11.    top:expression(this.offsetParent.scrollTop);     
  12.    z-index: 10;  
  13.    }  
  14. .Freezing th{text-overflow:ellipsis;overflow:hidden;white-space: nowrap;padding:2px;}  
  15. </style>   
  16. </head>  
  17. <body style="font-size=12px">  
  18.     <form id="form1" runat="server">  
  19.     <div style="overflow-y: scroll; height: 200px;width:300px" id="dvBody">  
  20.                    <asp:GridView ID="GridView1" runat="server"    AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"  
  21.                         OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowCreated="GridView1_RowCreated"  >  
  22.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  23.                         <Columns>  
  24.                             <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  25.                             <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" />  
  26.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  />  
  27.                             <asp:BoundField DataField="姓名" HeaderText="姓名"  />  
  28.                               
  29.                         </Columns>  
  30.                         <RowStyle ForeColor="#000066" />  
  31.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  32.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left"  CssClass="ms-formlabel DataGridFixedHeader"/>  
  33.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" CssClass="Freezing"/>  
  34.                     </asp:GridView>  
  35.         </div>  
  36.     </form>  
  37. </body>  
  38. </html>  
用法:CSS设如上的样式,HeaderStyle加CssClass="Freezing,套住GridView的Div设置高度宽度 <div style="overflow-y: scroll; height: 200px;width:200px" >

GridView合并表头多重表头无错完美版(以合并3列3行举例)

效果图:


后台代码:

[csharp] view plaincopyprint?
  1. using System;    
  2. using System.Data;    
  3. using System.Configuration;    
  4. using System.Web;    
  5. using System.Web.Security;    
  6. using System.Web.UI;    
  7. using System.Web.UI.WebControls;    
  8. using System.Web.UI.WebControls.WebParts;    
  9. using System.Web.UI.HtmlControls;    
  10. using System.Data.SqlClient;    
  11. using System.Drawing;    
  12. public partial class _Default : System.Web.UI.Page     
  13. {    
  14.     SqlConnection sqlcon;    
  15.     SqlCommand sqlcom;    
  16.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";    
  17.     protected void Page_Load(object sender, EventArgs e)    
  18.     {    
  19.         if (!IsPostBack)    
  20.         {    
  21.             bind();    
  22.                 
  23.         }    
  24.     }    
  25.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)    
  26.     {    
  27.         GridView1.EditIndex = e.NewEditIndex;    
  28.         bind();    
  29.     }    
  30.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)    
  31.     {    
  32.         sqlcon = new SqlConnection(strCon);    
  33.         string sqlstr = "update 飞狐工作室 set 姓名='"    
  34.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"    
  35.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"     
  36.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";    
  37.         sqlcom=new SqlCommand(sqlstr,sqlcon);    
  38.         sqlcon.Open();    
  39.         sqlcom.ExecuteNonQuery();    
  40.         sqlcon.Close();    
  41.         GridView1.EditIndex = -1;    
  42.         bind();    
  43.     }    
  44.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)    
  45.     {    
  46.         GridView1.EditIndex = -1;    
  47.         bind();    
  48.     }    
  49.     public void bind()    
  50.     {    
  51.         string sqlstr = "select top 10 * from 飞狐工作室";    
  52.         sqlcon = new SqlConnection(strCon);    
  53.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);    
  54.         DataSet myds = new DataSet();    
  55.         sqlcon.Open();    
  56.         myda.Fill(myds, "飞狐工作室");    
  57.         GridView1.DataSource = myds;    
  58.         GridView1.DataKeyNames = new string[] { "身份证号码" };    
  59.         GridView1.DataBind();    
  60.         sqlcon.Close();    
  61.     }    
  62. //这里就是解决方案     
  63.     protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)    
  64.     {    
  65.         switch (e.Row.RowType)    
  66.         {    
  67.             case DataControlRowType.Header:    
  68.                 //第一行表头     
  69.                 TableCellCollection tcHeader = e.Row.Cells;    
  70.                 tcHeader.Clear();    
  71.                 tcHeader.Add(new TableHeaderCell());    
  72.                 tcHeader[0].Attributes.Add("rowspan""3"); //跨Row    
  73.                 tcHeader[0].Attributes.Add("bgcolor""white");    
  74.                 tcHeader[0].Text = "";    
  75.                 tcHeader.Add(new TableHeaderCell());    
  76.                 //tcHeader[1].Attributes.Add("bgcolor", "Red");    
  77.                 tcHeader[1].Attributes.Add("colspan""6"); //跨Column    
  78.                 tcHeader[1].Text = "全部信息</th></tr><tr>";    
  79.                 //第二行表头     
  80.                 tcHeader.Add(new TableHeaderCell());    
  81.                 tcHeader[2].Attributes.Add("bgcolor""DarkSeaGreen");    
  82.                 tcHeader[2].Text = "身份证号码";    
  83.                 tcHeader.Add(new TableHeaderCell());    
  84.                 tcHeader[3].Attributes.Add("bgcolor""LightSteelBlue");    
  85.                 tcHeader[3].Attributes.Add("colspan""2");    
  86.                 tcHeader[3].Text = "基本信息";    
  87.                 tcHeader.Add(new TableHeaderCell());    
  88.                 tcHeader[4].Attributes.Add("bgcolor""DarkSeaGreen");    
  89.                 tcHeader[4].Text = "福利";    
  90.                 tcHeader.Add(new TableHeaderCell());    
  91.                 tcHeader[5].Attributes.Add("bgcolor""LightSteelBlue");    
  92.                 tcHeader[5].Attributes.Add("colspan""2");    
  93.                 tcHeader[5].Text = "联系方式</th></tr><tr>";    
  94.                 //第三行表头     
  95.                 tcHeader.Add(new TableHeaderCell());    
  96.                 tcHeader[6].Attributes.Add("bgcolor""Khaki");    
  97.                 tcHeader[6].Text = "身份证号码";    
  98.                 tcHeader.Add(new TableHeaderCell());    
  99.                 tcHeader[7].Attributes.Add("bgcolor""Khaki");    
  100.                 tcHeader[7].Text = "姓名";    
  101.                 tcHeader.Add(new TableHeaderCell());    
  102.                 tcHeader[8].Attributes.Add("bgcolor""Khaki");    
  103.                 tcHeader[8].Text = "出生日期";    
  104.                 tcHeader.Add(new TableHeaderCell());    
  105.                 tcHeader[9].Attributes.Add("bgcolor""Khaki");    
  106.                 tcHeader[9].Text = "薪水";    
  107.                 tcHeader.Add(new TableHeaderCell());    
  108.                 tcHeader[10].Attributes.Add("bgcolor""Khaki");    
  109.                 tcHeader[10].Text = "家庭住址";    
  110.                 tcHeader.Add(new TableHeaderCell());    
  111.                 tcHeader[11].Attributes.Add("bgcolor""Khaki");    
  112.                 tcHeader[11].Text = "邮政编码";    
  113.                 break;    
  114.         }    
  115.     }    
  116. }  

前台:
[html] view plaincopyprint?
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" >  
  3. <head runat="server">  
  4.     <title>GridView合并多重表头表头 清清月儿http://blog.csdn.net/21aspnet </title>  
  5. </head>  
  6. <body >  
  7.     <form id="form1" runat="server">  
  8.     <div  >  
  9.                    <asp:GridView ID="GridView1" runat="server"    AutoGenerateColumns="False" CellPadding="3"  OnRowEditing="GridView1_RowEditing"  
  10.                         OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowCreated="GridView1_RowCreated"  >  
  11.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  12.                         <Columns>  
  13.                             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />  
  14.                             <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  15.                             <asp:BoundField DataField="姓名" HeaderText="姓名"  />  
  16.                             <asp:BoundField DataField="出生日期" HeaderText="邮政编码"  />  
  17.                              <asp:BoundField DataField="起薪" HeaderText="起薪"  />  
  18.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  />  
  19.                             <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" />  
  20.                              
  21.                         </Columns>  
  22.                         <RowStyle ForeColor="#000066" />  
  23.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  24.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left"  CssClass="ms-formlabel DataGridFixedHeader"/>  
  25.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  26.                     </asp:GridView>  
  27.         </div>  
  28.     </form>  
  29. </body>  
  30. </html>  

GridView突出显示某一单元格(例如金额低于多少,分数不及格等)

效果图:

解决方案:主要是绑定后过滤

[csharp] view plaincopyprint?
  1. GridView1.DataBind();  
  2.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  3.         {  
  4.             DataRowView mydrv = myds.Tables["飞狐工作室"].DefaultView[i];  
  5.             string score = Convert.ToString(mydrv["起薪"]);  
  6.             if (Convert.ToDouble(score) < 34297.00)//大家这里根据具体情况设置可能ToInt32等等  
  7.             {  
  8.                 GridView1.Rows[i].Cells[4].BackColor = System.Drawing.Color.Red;  
  9.             }  
  10.         }  
  11.         sqlcon.Close();  
全部后台代码:
[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Data.SqlClient;  
  11. using System.Drawing;  
  12. public partial class Default7 : System.Web.UI.Page  
  13. {  
  14.     SqlConnection sqlcon;  
  15.     SqlCommand sqlcom;  
  16.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  17.     protected void Page_Load(object sender, EventArgs e)  
  18.     {  
  19.         if (!IsPostBack)  
  20.         {  
  21.             bind();  
  22.         }  
  23.     }  
  24.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  25.     {  
  26.         GridView1.EditIndex = e.NewEditIndex;  
  27.         bind();  
  28.     }  
  29.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  30.     {  
  31.         sqlcon = new SqlConnection(strCon);  
  32.         string sqlstr = "update 飞狐工作室 set 姓名='"  
  33.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"  
  34.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"  
  35.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  36.         sqlcom = new SqlCommand(sqlstr, sqlcon);  
  37.         sqlcon.Open();  
  38.         sqlcom.ExecuteNonQuery();  
  39.         sqlcon.Close();  
  40.         GridView1.EditIndex = -1;  
  41.         bind();  
  42.     }  
  43.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  44.     {  
  45.         GridView1.EditIndex = -1;  
  46.         bind();  
  47.     }  
  48.     public void bind()  
  49.     {  
  50.         string sqlstr = "select top 10 * from 飞狐工作室";  
  51.         sqlcon = new SqlConnection(strCon);  
  52.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  53.         DataSet myds = new DataSet();  
  54.         sqlcon.Open();  
  55.         myda.Fill(myds, "飞狐工作室");  
  56.         GridView1.DataSource = myds;  
  57.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  58.         GridView1.DataBind();  
  59.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  60.         {  
  61.             DataRowView mydrv = myds.Tables["飞狐工作室"].DefaultView[i];  
  62.             string score = Convert.ToString(mydrv["起薪"]);  
  63.             if (Convert.ToDouble(score) < 34297.00)//大家这里根据具体情况设置可能ToInt32等等  
  64.   
  65.             {  
  66.                 GridView1.Rows[i].Cells[4].BackColor = System.Drawing.Color.Red;  
  67.             }  
  68.         }  
  69.         sqlcon.Close();  
  70.     }  
  71. }  
前台代码:
[html] view plaincopyprint?
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" >  
  3. <head id="Head1" runat="server">  
  4.     <title>GridView突出显示某一单元格 清清月儿http://blog.csdn.net/21aspnet </title>  
  5. </head>  
  6. <body >  
  7.     <form id="form1" runat="server">  
  8.     <div  >  
  9.                    <asp:GridView ID="GridView1" runat="server"    AutoGenerateColumns="False" CellPadding="3"  OnRowEditing="GridView1_RowEditing"  
  10.                         OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px"  >  
  11.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  12.                         <Columns>  
  13.                             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />  
  14.                             <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  15.                             <asp:BoundField DataField="姓名" HeaderText="姓名"  />  
  16.                             <asp:BoundField DataField="出生日期" HeaderText="邮政编码"  />  
  17.                              <asp:BoundField DataField="起薪" HeaderText="起薪"  DataFormatString="{0:C}" HtmlEncode="false"/>  
  18.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  />  
  19.                             <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" />  
  20.                              
  21.                         </Columns>  
  22.                         <RowStyle ForeColor="#000066" />  
  23.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  24.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left"  CssClass="ms-formlabel DataGridFixedHeader"/>  
  25.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  26.                     </asp:GridView>  
  27.         </div>  
  28.     </form>  
  29. </body>  
  30. </html>  

GridView加入自动求和求平均值小计

效果图:
解决方案: 

[csharp] view plaincopyprint?
  1. private double sum = 0;//取指定列的数据和,你要根据具体情况对待可能你要处理的是int  
  2. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  3.     {  
  4.           
  5.         if (e.Row.RowIndex >= 0)  
  6.         {  
  7.             sum += Convert.ToDouble(e.Row.Cells[6].Text);  
  8.         }  
  9.         else if (e.Row.RowType == DataControlRowType.Footer)  
  10.         {  
  11.             e.Row.Cells[5].Text = "总薪水为:";  
  12.             e.Row.Cells[6].Text = sum.ToString();  
  13.             e.Row.Cells[3].Text = "平均薪水为:";  
  14.             e.Row.Cells[4].Text = ((int)(sum / GridView1.Rows.Count)).ToString();  
  15.               
  16.         }  
  17.     }  
后台全部代码:
[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Data.SqlClient;  
  11. using System.Drawing;  
  12. public partial class Default7 : System.Web.UI.Page  
  13. {  
  14.     SqlConnection sqlcon;  
  15.     SqlCommand sqlcom;  
  16.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  17.     protected void Page_Load(object sender, EventArgs e)  
  18.     {  
  19.         if (!IsPostBack)  
  20.         {  
  21.             bind();  
  22.         }  
  23.     }  
  24.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  25.     {  
  26.         GridView1.EditIndex = e.NewEditIndex;  
  27.         bind();  
  28.     }  
  29.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  30.     {  
  31.         sqlcon = new SqlConnection(strCon);  
  32.         string sqlstr = "update 飞狐工作室 set 姓名='"  
  33.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"  
  34.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"  
  35.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  36.         sqlcom = new SqlCommand(sqlstr, sqlcon);  
  37.         sqlcon.Open();  
  38.         sqlcom.ExecuteNonQuery();  
  39.         sqlcon.Close();  
  40.         GridView1.EditIndex = -1;  
  41.         bind();  
  42.     }  
  43.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  44.     {  
  45.         GridView1.EditIndex = -1;  
  46.         bind();  
  47.     }  
  48.     public void bind()  
  49.     {  
  50.         string sqlstr = "select top 5 * from 飞狐工作室";  
  51.         sqlcon = new SqlConnection(strCon);  
  52.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  53.         DataSet myds = new DataSet();  
  54.         sqlcon.Open();  
  55.         myda.Fill(myds, "飞狐工作室");  
  56.         GridView1.DataSource = myds;  
  57.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  58.         GridView1.DataBind();  
  59.         sqlcon.Close();  
  60.     }  
  61.     private double sum = 0;//取指定列的数据和  
  62.     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  63.     {  
  64.           
  65.         if (e.Row.RowIndex >= 0)  
  66.         {  
  67.             sum += Convert.ToDouble(e.Row.Cells[6].Text);  
  68.         }  
  69.         else if (e.Row.RowType == DataControlRowType.Footer)  
  70.         {  
  71.             e.Row.Cells[5].Text = "总薪水为:";  
  72.             e.Row.Cells[6].Text = sum.ToString();  
  73.             e.Row.Cells[3].Text = "平均薪水为:";  
  74.             e.Row.Cells[4].Text = ((int)(sum / GridView1.Rows.Count)).ToString();  
  75.               
  76.         }  
  77.     }  
  78. }  
前台:唯一的花头就是设置ShowFooter="True" ,否则默认表头为隐藏的!
[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server"    AutoGenerateColumns="False" CellPadding="3"  OnRowEditing="GridView1_RowEditing"  
  2.                         OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound" ShowFooter="True"  >  
  3.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  4.                         <Columns>  
  5.                             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />  
  6.                             <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  7.                             <asp:BoundField DataField="姓名" HeaderText="姓名"  />  
  8.                             <asp:BoundField DataField="出生日期" HeaderText="邮政编码"  />  
  9.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  />  
  10.                             <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" />  
  11.                             <asp:BoundField DataField="起薪" HeaderText="起薪"  />  
  12.                              
  13.                         </Columns>  
  14.                         <RowStyle ForeColor="#000066" />  
  15.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  16.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left"  CssClass="ms-formlabel DataGridFixedHeader"/>  
  17.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  18.                     </asp:GridView>  

GridView数据导入Excel/Excel数据读入GridView

效果图:

解决方案:
页面增加一个按钮,单击事件添加如下方法:

[csharp] view plaincopyprint?
  1. protected void Button1_Click(object sender, EventArgs e)  
  2.     {  
  3.         Export("application/ms-excel""学生成绩报表.xls");  
  4.     }  
  5.     private void Export(string FileType, string FileName)  
  6.     {  
  7.         Response.Charset = "GB2312";  
  8.         Response.ContentEncoding = System.Text.Encoding.UTF7;  
  9.         Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());  
  10.         Response.ContentType = FileType;  
  11.         this.EnableViewState = false;  
  12.         StringWriter tw = new StringWriter();  
  13.         HtmlTextWriter hw = new HtmlTextWriter(tw);  
  14.         GridView1.RenderControl(hw);  
  15.         Response.Write(tw.ToString());  
  16.         Response.End();  
  17.     }  
  18. //如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内  
  19.     public override void VerifyRenderingInServerForm(Control control)  
  20.     {  
  21.     }  

还有由于是文件操作所以要引入名称空间IO和Text

后台代码:

[csharp] view plaincopyprint?
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Data.SqlClient;  
  11. using System.Drawing;  
  12. using System.IO;  
  13. using System.Text;  
  14. public partial class Default7 : System.Web.UI.Page  
  15. {  
  16.     SqlConnection sqlcon;  
  17.     SqlCommand sqlcom;  
  18.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  19.     protected void Page_Load(object sender, EventArgs e)  
  20.     {  
  21.         if (!IsPostBack)  
  22.         {  
  23.             bind();  
  24.         }  
  25.     }  
  26.       
  27.     public void bind()  
  28.     {  
  29.         string sqlstr = "select top 5 * from 飞狐工作室";  
  30.         sqlcon = new SqlConnection(strCon);  
  31.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  32.         DataSet myds = new DataSet();  
  33.         sqlcon.Open();  
  34.         myda.Fill(myds, "飞狐工作室");  
  35.         GridView1.DataSource = myds;  
  36.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  37.         GridView1.DataBind();  
  38.         sqlcon.Close();  
  39.     }  
  40.     protected void Button1_Click(object sender, EventArgs e)  
  41.     {  
  42.         Export("application/ms-excel""学生成绩报表.xls");  
  43.     }  
  44.     private void Export(string FileType, string FileName)  
  45.     {  
  46.         Response.Charset = "GB2312";  
  47.         Response.ContentEncoding = System.Text.Encoding.UTF7;  
  48.         Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());  
  49.         Response.ContentType = FileType;  
  50.         this.EnableViewState = false;  
  51.         StringWriter tw = new StringWriter();  
  52.         HtmlTextWriter hw = new HtmlTextWriter(tw);  
  53.         GridView1.RenderControl(hw);  
  54.         Response.Write(tw.ToString());  
  55.         Response.End();  
  56.     }  
  57.     public override void VerifyRenderingInServerForm(Control control)  
  58.     {  
  59.     }  
  60.       
  61. }  
前台
[html] view plaincopyprint?
  1. <asp:GridView ID="GridView1" runat="server"    AutoGenerateColumns="False" CellPadding="3"    
  2.                          BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px"   >  
  3.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  4.                         <Columns>  
  5.                             <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  6.                             <asp:BoundField DataField="姓名" HeaderText="姓名"  />  
  7.                             <asp:BoundField DataField="出生日期" HeaderText="邮政编码"  />  
  8.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  />  
  9.                             <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" />  
  10.                             <asp:BoundField DataField="起薪" HeaderText="起薪"  />  
  11.                              
  12.                         </Columns>  
  13.                         <RowStyle ForeColor="#000066" />  
  14.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  15.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left"  CssClass="ms-formlabel DataGridFixedHeader"/>  
  16.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  17.                     </asp:GridView>  
  18.         <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出" />  
读取Excel数据的代码:这个很简单的
[csharp] view plaincopyprint?
  1. private DataSet CreateDataSource()  
  2.     {  
  3.         string strCon;  
  4.         strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("excel.xls") + "; Extended Properties=Excel 8.0;";  
  5.         OleDbConnection olecon = new OleDbConnection(strCon);  
  6.         OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strCon);  
  7.         DataSet myds = new DataSet();  
  8.         myda.Fill(myds);  
  9.         return myds;  
  10.     }  
  11.     protected void Button1_Click(object sender, EventArgs e)  
  12.     {  
  13.         GridView1.DataSource = CreateDataSource();  
  14.         GridView1.DataBind();  
  15.     }