Asp.net中GridView使用详解

 

l         GridView无代码分页排序

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

l         GridView正反双向排序

l         GridView和下拉菜单DropDownList结合

l         GridView和CheckBox结合

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

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

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

l         GridView实现自动编号

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

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

l         GridView一般换行与强制换行

l         GridView显示隐藏某一列

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

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

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

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

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

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

1.GridView简单代码分页排序:

 

1.AllowSorting设为True,aspx代码中是AllowSorting="True";

2.默认1页10条,如果要修改每页条数,修改PageSize即可,在aspx代码中是PageSize="12"。

3.默认的是单向排序的,右击GridView弹出“属性”,选择AllowSorting为True即可。

4.添加代码:

[csharp] view plain copy

 

  1. protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  2.    {  
  3.        GridView1.PageIndex = e.NewPageIndex;  
  4.        Bind();  
  5.    }  

 

2.GridView选中,编辑,取消,删除:

后台代码:

 

[csharp] view plain copy

 

  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=帐号;Pwd=密码";  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.         if (!IsPostBack)  
  19.         {  
  20.             bind();  
  21.         }  
  22.     }  
  23.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  24.     {  
  25.         GridView1.EditIndex = e.NewEditIndex;  
  26.         bind();  
  27.     }  
  28. //删除  
  29.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  30.     {  
  31.         string sqlstr = "delete from 表 where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  32.         sqlcon = new SqlConnection(strCon);  
  33.         sqlcom = new SqlCommand(sqlstr,sqlcon);  
  34.         sqlcon.Open();  
  35.         sqlcom.ExecuteNonQuery();  
  36.         sqlcon.Close();  
  37.         bind();  
  38.     }  
  39. //更新  
  40.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  41.     {  
  42.         sqlcon = new SqlConnection(strCon);  
  43.         string sqlstr = "update 表 set 字段1='"  
  44.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',字段2='"  
  45.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',字段3='"  
  46.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where id='"  
  47.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  48.         sqlcom=new SqlCommand(sqlstr,sqlcon);  
  49.         sqlcon.Open();  
  50.         sqlcom.ExecuteNonQuery();  
  51.         sqlcon.Close();  
  52.         GridView1.EditIndex = -1;  
  53.         bind();  
  54.     }  
  55. //取消  
  56.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  57.     {  
  58.         GridView1.EditIndex = -1;  
  59.         bind();  
  60.     }  
  61. //绑定  
  62.     public void bind()  
  63.     {  
  64.         string sqlstr = "select * from 表";  
  65.         sqlcon = new SqlConnection(strCon);  
  66.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  67.         DataSet myds = new DataSet();  
  68.         sqlcon.Open();  
  69.         myda.Fill(myds, "表");  
  70.         GridView1.DataSource = myds;  
  71.         GridView1.DataKeyNames = new string[] { "id" };//主键  
  72.         GridView1.DataBind();  
  73.         sqlcon.Close();  
  74.     }  
  75. }  


前台主要代码:

[csharp] view plain copy

 

  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>  

 

3.GridView正反双向排序:

 

后台代码:

[csharp] view plain copy

 

  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. {    SqlConnection sqlcon;  
  14.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=";  
  15.     protected void Page_Load(object sender, EventArgs e)  
  16.     {  
  17.         if (!IsPostBack)  
  18.         {  
  19.             ViewState["SortOrder"] = "身份证号码";  
  20.             ViewState["OrderDire"] = "ASC";  
  21.             bind();  
  22.         }  
  23.     }  
  24.     protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)  
  25.     {  
  26.         string sPage = e.SortExpression;  
  27.         if (ViewState["SortOrder"].ToString() == sPage)  
  28.         {  
  29.             if (ViewState["OrderDire"].ToString() == "Desc")  
  30.                 ViewState["OrderDire"] = "ASC";  
  31.             else  
  32.                 ViewState["OrderDire"] = "Desc";  
  33.         }  
  34.         else  
  35.         {  
  36.             ViewState["SortOrder"] = e.SortExpression;  
  37.         }  
  38.         bind();  
  39.     }  
  40.     public void bind()  
  41.     {  
  42.          
  43.         string sqlstr = "select top 5 * from 飞狐工作室";  
  44.         sqlcon = new SqlConnection(strCon);  
  45.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  46.         DataSet myds = new DataSet();  
  47.         sqlcon.Open();  
  48.         myda.Fill(myds, "飞狐工作室");  
  49.         DataView view = myds.Tables["飞狐工作室"].DefaultView;  
  50.         string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];  
  51.         view.Sort = sort;  
  52.         GridView1.DataSource = view;  
  53.         GridView1.DataBind();  
  54.         sqlcon.Close();  
  55.     }  
  56. }  


前台主要代码:

[csharp] view plain copy

 

  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.                         </Columns>  
  10.                         <RowStyle ForeColor="#000066" />  
  11.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  12.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  13.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  14.                     </asp:GridView>   

4.GridView和下拉菜单DropDownList结合:

 

后台代码:

[csharp] view plain copy

 

  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.     }  


前台主要代码:

[csharp] view plain copy

 

  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>  

 

5.GridView和CheckBox结合:

 

后台代码:

[csharp] view plain copy

 

  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.     SqlConnection sqlcon;  
  14.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  15.     protected void Page_Load(object sender, EventArgs e)  
  16.     {  
  17.         if (!IsPostBack)  
  18.         {  
  19.             bind();  
  20.         }  
  21.     }  
  22.     protected void CheckBox2_CheckedChanged(object sender, EventArgs e)  
  23.     {  
  24.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  25.         {  
  26.             CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");  
  27.             if (CheckBox2.Checked == true)  
  28.             {  
  29.                 cbox.Checked = true;  
  30.             }  
  31.             else  
  32.             {  
  33.                 cbox.Checked = false;  
  34.             }  
  35.         }  
  36.     }  
  37.     protected void Button2_Click(object sender, EventArgs e)  
  38.     {  
  39.         sqlcon = new SqlConnection(strCon);  
  40.         SqlCommand sqlcom;  
  41.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  42.         {  
  43.             CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");  
  44.             if (cbox.Checked == true)  
  45.             {  
  46.                 string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[i].Value + "'";  
  47.                 sqlcom = new SqlCommand(sqlstr, sqlcon);  
  48.                 sqlcon.Open();  
  49.                 sqlcom.ExecuteNonQuery();  
  50.                 sqlcon.Close();  
  51.             }  
  52.         }  
  53.         bind();  
  54.     }  
  55.     protected void Button1_Click(object sender, EventArgs e)  
  56.     {  
  57.         CheckBox2.Checked = false;  
  58.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  59.         {  
  60.             CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");  
  61.             cbox.Checked = false;  
  62.         }  
  63.     }  
  64.     public void bind()  
  65.     {  
  66.         string sqlstr = "select top 5 * from 飞狐工作室";  
  67.         sqlcon = new SqlConnection(strCon);  
  68.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  69.         DataSet myds = new DataSet();  
  70.         sqlcon.Open();  
  71.         myda.Fill(myds, "tb_Member");  
  72.         GridView1.DataSource = myds;  
  73.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  74.         GridView1.DataBind();  
  75.         sqlcon.Close();  
  76.     }  
  77. }  

前台主要代码:

[csharp] view plain copy

 

  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" />  

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

 

做法:

双击GridView的OnRowDataBound事件;

在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:

[csharp] view plain copy

 

  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.     {  
  3. //首先判断是否是数据行  
  4.             if (e.Row.RowType == DataControlRowType.DataRow)  
  5.             {  
  6.                 //当鼠标停留时更改背景色  
  7.                 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");  
  8.                 //当鼠标移开时还原背景色  
  9.                 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");  
  10.             }  
  11.     }  


前台代码:

[csharp] view plain copy

 

  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>  

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

 

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

[csharp] view plain copy

 

  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.     {  
  3.         //如果是绑定数据行  
  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.         }  
  11.     }  

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

 

实现方法:

双击GridView的OnRowDataBound事件;

在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:

[csharp] view plain copy

 

  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.     }  

 

9.GridView实现自动编号:

 

实现方法:

双击GridView的OnRowDataBound事件;

在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:

[csharp] view plain copy

 

  1. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  2. {  
  3.     if (e.Row.RowIndex != -1)  
  4.     {  
  5.         int id = e.Row.RowIndex + 1;  
  6.         e.Row.Cells[0].Text = id.ToString();  
  7.     }  
  8. }  


注意这时最好把前台的第一列的表头该为“编号”,因为以前的第一列被“吃掉”了。

[csharp] view plain copy

 

  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>  

 

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

 

 

解决方法:

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

[csharp] view plain copy

 

  1. <asp :BoundField DataField="CreationDate"  
  2. DataFormatString="{0:M-dd-yyyy}"  
  3. HeaderText="CreationDate" />  

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

1、

[csharp] view plain copy

 

  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即可

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

[csharp] view plain copy

 

  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>  

 

前台代码:

[csharp] view plain copy

 

  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

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

 

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

[csharp] view plain copy

 

  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 plain copy

 

  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. }  

 

12.GridView一般换行与强制换行:

 

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

[csharp] view plain copy

 

  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。

13.GridView显示隐藏某一列:

 

 

解决方案:

[csharp] view plain copy

 

  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 plain copy

 

  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 plain copy

 

  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.   
  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.             ViewState["SortOrder"] = "身份证号码";  
  22.             ViewState["OrderDire"] = "ASC";  
  23.             bind();  
  24.                    }  
  25.     }  
  26.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  27.     {  
  28.         GridView1.EditIndex = e.NewEditIndex;  
  29.         bind();  
  30.     }  
  31.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  32.     {  
  33.         string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  34.         sqlcon = new SqlConnection(strCon);  
  35.         sqlcom = new SqlCommand(sqlstr,sqlcon);  
  36.         sqlcon.Open();  
  37.         sqlcom.ExecuteNonQuery();  
  38.         sqlcon.Close();  
  39.         bind();  
  40.     }  
  41.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  42.     {  
  43.         sqlcon = new SqlConnection(strCon);  
  44.         string sqlstr = "update 飞狐工作室 set 姓名='"  
  45.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"  
  46.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"   
  47.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  48.         sqlcom=new SqlCommand(sqlstr,sqlcon);  
  49.         sqlcon.Open();  
  50.         sqlcom.ExecuteNonQuery();  
  51.         sqlcon.Close();  
  52.         GridView1.EditIndex = -1;  
  53.         bind();  
  54.     }  
  55.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  56.     {  
  57.         GridView1.EditIndex = -1;  
  58.         bind();  
  59.     }  
  60.     public void bind()  
  61.     {  
  62.         string sqlstr = "select top 5 * from 飞狐工作室";  
  63.         sqlcon = new SqlConnection(strCon);  
  64.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  65.         DataSet myds = new DataSet();  
  66.         sqlcon.Open();  
  67.         myda.Fill(myds, "飞狐工作室");  
  68.         GridView1.DataSource = myds;  
  69.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  70.         GridView1.DataBind();  
  71.         sqlcon.Close();  
  72.         GridView1.Columns[3].Visible = false;  
  73.         CheckBox1.Checked = false;  
  74.     }  
  75.     protected void CheckBox1_CheckedChanged(object sender, EventArgs e)  
  76.     {  
  77.          GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible;  
  78.          Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString());  
  79.     }  
  80. }  

前台代码:

[csharp] view plain copy

 

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2.   
  3. <html xmlns="http://www.w3.org/1999/xhtml" >  
  4. <head runat="server">  
  5.     <title>GridView显示隐藏列 清清月儿http://blog.csdn.net/21aspnet </title>  
  6. </head>  
  7. <body style="font-size=12px">  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"  
  11.                         OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px"  >  
  12.                         <FooterStyle BackColor="White" ForeColor="#000066" />  
  13.                         <Columns>  
  14.                             <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />  
  15.                             <asp:BoundField DataField="姓名" HeaderText="用户姓名" />  
  16.                             <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" />  
  17.                             <asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  />  
  18.                             <asp:CommandField HeaderText="选择" ShowSelectButton="True" />  
  19.                             <asp:CommandField HeaderText="编辑" ShowEditButton="True" />  
  20.                             <asp:CommandField HeaderText="删除" ShowDeleteButton="True" />  
  21.                         </Columns>  
  22.                         <RowStyle ForeColor="#000066" />  
  23.                         <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />  
  24.                         <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />  
  25.                         <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />  
  26.                     </asp:GridView>  
  27.         <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" Font-Size="12px"  
  28.             OnCheckedChanged="CheckBox1_CheckedChanged" Text="显示隐藏家庭住址" /></div>  
  29.     </form>  
  30. </body>  
  31. </html>  

 

14.GridView弹出新页面:

 

[csharp] view plain copy

 

  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是路径。

15.GridView固定表头(不用JavaScript只用CSS!,很好用):

 

代码:

[csharp] view plain copy

 

  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" >

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

 

后台代码:

  

[csharp] view plain copy

 

  1. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)  
  2.     {  
  3.         switch (e.Row.RowType)  
  4.         {  
  5.             case DataControlRowType.Header:  
  6.                 //第一行表头  
  7.                 TableCellCollection tcHeader = e.Row.Cells;  
  8.                 tcHeader.Clear();  
  9.                 tcHeader.Add(new TableHeaderCell());  
  10.                 tcHeader[0].Attributes.Add("rowspan", "3"); //跨Row  
  11.                 tcHeader[0].Attributes.Add("bgcolor", "white");  
  12.                 tcHeader[0].Text = "";  
  13.                 tcHeader.Add(new TableHeaderCell());  
  14.                 //tcHeader[1].Attributes.Add("bgcolor", "Red");  
  15.                 tcHeader[1].Attributes.Add("colspan", "6"); //跨Column  
  16.                 tcHeader[1].Text = "全部信息</th></tr><tr>";  
  17.                 //第二行表头  
  18.                 tcHeader.Add(new TableHeaderCell());  
  19.                 tcHeader[2].Attributes.Add("bgcolor", "DarkSeaGreen");  
  20.                 tcHeader[2].Text = "身份证号码";  
  21.                 tcHeader.Add(new TableHeaderCell());  
  22.                 tcHeader[3].Attributes.Add("bgcolor", "LightSteelBlue");  
  23.                 tcHeader[3].Attributes.Add("colspan", "2");  
  24.                 tcHeader[3].Text = "基本信息";  
  25.                 tcHeader.Add(new TableHeaderCell());  
  26.                 tcHeader[4].Attributes.Add("bgcolor", "DarkSeaGreen");  
  27.                 tcHeader[4].Text = "福利";  
  28.                 tcHeader.Add(new TableHeaderCell());  
  29.                 tcHeader[5].Attributes.Add("bgcolor", "LightSteelBlue");  
  30.                 tcHeader[5].Attributes.Add("colspan", "2");  
  31.                 tcHeader[5].Text = "联系方式</th></tr><tr>";  
  32.                 //第三行表头  
  33.                 tcHeader.Add(new TableHeaderCell());  
  34.                 tcHeader[6].Attributes.Add("bgcolor", "Khaki");  
  35.                 tcHeader[6].Text = "身份证号码";  
  36.                 tcHeader.Add(new TableHeaderCell());  
  37.                 tcHeader[7].Attributes.Add("bgcolor", "Khaki");  
  38.                 tcHeader[7].Text = "姓名";  
  39.                 tcHeader.Add(new TableHeaderCell());  
  40.                 tcHeader[8].Attributes.Add("bgcolor", "Khaki");  
  41.                 tcHeader[8].Text = "出生日期";  
  42.                 tcHeader.Add(new TableHeaderCell());  
  43.                 tcHeader[9].Attributes.Add("bgcolor", "Khaki");  
  44.                 tcHeader[9].Text = "薪水";  
  45.                 tcHeader.Add(new TableHeaderCell());  
  46.                 tcHeader[10].Attributes.Add("bgcolor", "Khaki");  
  47.                 tcHeader[10].Text = "家庭住址";  
  48.                 tcHeader.Add(new TableHeaderCell());  
  49.                 tcHeader[11].Attributes.Add("bgcolor", "Khaki");  
  50.                 tcHeader[11].Text = "邮政编码";  
  51.                 break;  
  52.         }  
  53.     }  
  54. }  

前台:

[csharp] view plain copy

 

  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>  

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

 

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

[csharp] view plain copy

 

  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 plain copy

 

  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.   
  13. public partial class Default7 : System.Web.UI.Page  
  14. {  
  15.     SqlConnection sqlcon;  
  16.     SqlCommand sqlcom;  
  17.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  18.     protected void Page_Load(object sender, EventArgs e)  
  19.     {  
  20.         if (!IsPostBack)  
  21.         {  
  22.             bind();  
  23.   
  24.         }  
  25.     }  
  26.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  27.     {  
  28.         GridView1.EditIndex = e.NewEditIndex;  
  29.         bind();  
  30.     }  
  31.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  32.     {  
  33.         sqlcon = new SqlConnection(strCon);  
  34.         string sqlstr = "update 飞狐工作室 set 姓名='"  
  35.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"  
  36.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"  
  37.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  38.         sqlcom = new SqlCommand(sqlstr, sqlcon);  
  39.         sqlcon.Open();  
  40.         sqlcom.ExecuteNonQuery();  
  41.         sqlcon.Close();  
  42.         GridView1.EditIndex = -1;  
  43.         bind();  
  44.     }  
  45.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  46.     {  
  47.         GridView1.EditIndex = -1;  
  48.         bind();  
  49.     }  
  50.     public void bind()  
  51.     {  
  52.         string sqlstr = "select top 10 * from 飞狐工作室";  
  53.         sqlcon = new SqlConnection(strCon);  
  54.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  55.         DataSet myds = new DataSet();  
  56.         sqlcon.Open();  
  57.         myda.Fill(myds, "飞狐工作室");  
  58.         GridView1.DataSource = myds;  
  59.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  60.         GridView1.DataBind();  
  61.         for (int i = 0; i <= GridView1.Rows.Count - 1; i++)  
  62.         {  
  63.             DataRowView mydrv = myds.Tables["飞狐工作室"].DefaultView[i];  
  64.             string score = Convert.ToString(mydrv["起薪"]);  
  65.             if (Convert.ToDouble(score) < 34297.00)//大家这里根据具体情况设置可能ToInt32等等  
  66.   
  67.             {  
  68.                 GridView1.Rows[i].Cells[4].BackColor = System.Drawing.Color.Red;  
  69.             }  
  70.         }  
  71.         sqlcon.Close();  
  72.     }  
  73. }  

 

前台代码:

[csharp] view plain copy

 

  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>  

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

 

解决方案

[csharp] view plain copy

 

  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 plain copy

 

  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.   
  13. public partial class Default7 : System.Web.UI.Page  
  14. {  
  15.     SqlConnection sqlcon;  
  16.     SqlCommand sqlcom;  
  17.     string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";  
  18.     protected void Page_Load(object sender, EventArgs e)  
  19.     {  
  20.         if (!IsPostBack)  
  21.         {  
  22.             bind();  
  23.   
  24.         }  
  25.     }  
  26.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  27.     {  
  28.         GridView1.EditIndex = e.NewEditIndex;  
  29.         bind();  
  30.     }  
  31.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  32.     {  
  33.         sqlcon = new SqlConnection(strCon);  
  34.         string sqlstr = "update 飞狐工作室 set 姓名='"  
  35.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"  
  36.             + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"  
  37.             + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";  
  38.         sqlcom = new SqlCommand(sqlstr, sqlcon);  
  39.         sqlcon.Open();  
  40.         sqlcom.ExecuteNonQuery();  
  41.         sqlcon.Close();  
  42.         GridView1.EditIndex = -1;  
  43.         bind();  
  44.     }  
  45.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  46.     {  
  47.         GridView1.EditIndex = -1;  
  48.         bind();  
  49.     }  
  50.     public void bind()  
  51.     {  
  52.         string sqlstr = "select top 5 * from 飞狐工作室";  
  53.         sqlcon = new SqlConnection(strCon);  
  54.         SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);  
  55.         DataSet myds = new DataSet();  
  56.         sqlcon.Open();  
  57.         myda.Fill(myds, "飞狐工作室");  
  58.         GridView1.DataSource = myds;  
  59.         GridView1.DataKeyNames = new string[] { "身份证号码" };  
  60.         GridView1.DataBind();  
  61.         sqlcon.Close();  
  62.     }  
  63.     private double sum = 0;//取指定列的数据和  
  64.     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
  65.     {  
  66.           
  67.         if (e.Row.RowIndex >= 0)  
  68.         {  
  69.             sum += Convert.ToDouble(e.Row.Cells[6].Text);  
  70.         }  
  71.         else if (e.Row.RowType == DataControlRowType.Footer)  
  72.         {  
  73.             e.Row.Cells[5].Text = "总薪水为:";  
  74.             e.Row.Cells[6].Text = sum.ToString();  
  75.             e.Row.Cells[3].Text = "平均薪水为:";  
  76.             e.Row.Cells[4].Text = ((int)(sum / GridView1.Rows.Count)).ToString();  
  77.               
  78.         }  
  79.     }  
  80. }  

 

前台:唯一的花头就是设置ShowFooter="True" ,否则默认表头为隐藏的!

[csharp] view plain copy

 

  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>   

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

 

解决方案:

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

[csharp] view plain copy

 

  1. <pre name="code" class="csharp">protected void Button2_Click(object sender, EventArgs e)  
  2.         {  
  3.             //Response.Clear();  
  4.             //Response.AddHeader("content-disposition", "attachment;filename=MES.xls");  
  5.             //Response.ContentType = "application/vnd.ms-excel";  
  6.             //Response.ContentEncoding = System.Text.Encoding.Default;  
  7.             //System.IO.StringWriter sw = new System.IO.StringWriter();  
  8.             //System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);  
  9.             //GridView1.RenderControl(hw);  
  10.             //Response.Write(sw.ToString());  
  11.             //Response.Flush();  
  12.             //Response.End();//这段会出现乱码,一般使用下面的方法转换一下  
  13.   
  14.             Response.Clear();  
  15.             Response.Buffer = true;  
  16.             Response.Charset = "GB2312";  
  17.             Response.AppendHeader("Content-Disposition", "attachment;filename=Message.xls");  
  18.             Response.ContentEncoding = System.Text.Encoding.UTF8;  
  19.             Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。   
  20.             System.IO.StringWriter oStringWriter = new System.IO.StringWriter();  
  21.             System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);  
  22.             this.GridView1.RenderControl(oHtmlTextWriter);  
  23.             Response.Output.Write(oStringWriter.ToString());  
  24.             Response.Flush();  
  25.             Response.End();  
  26.         }  
  27.         public override void VerifyRenderingInServerForm(Control control)  
  28.         {  
  29.             //此段必须要,否则会报错,数据不能导入到EXCEL。  
  30.         }  


 

//如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内

[csharp] view plain copy

 

  1. public override void VerifyRenderingInServerForm(Control control)  
  2. {  
  3. }  

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

后台代码:

[csharp] view plain copy

 

  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. }  

前台:

[csharp] view plain copy

 

  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 plain copy

 

    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.     }  

 

https://blog.csdn.net/qq_38819293/article/details/81610333

posted @ 2023-02-03 11:02  Rukh  阅读(258)  评论(0编辑  收藏  举报