Asp.net中GridView使用详解
------------------------------------------------
目录
-------------------------------------------------
1、GridView无代码分页排序
2、GridView选中,编辑,取消,删除
3、GridView正反双向排序
4、GridView和下拉菜单DropDownList结合
5、GridView和CheckBox结合
6、鼠标移到GridView某一行时改变该行的背景色方法一
7、鼠标移到GridView某一行时改变该行的背景色方法二
8、GridView实现删除时弹出确认对话框
9、GridView实现自动编号
10、GridView实现自定义时间货币等字符串格式
11、GridView实现用“...”代替超长字符串
12、GridView一般换行与强制换行
13、GridView显示隐藏某一列
14、GridView弹出新页面/弹出新窗口
15、GridView固定表头(不用javascript只用CSS,2行代码,很好用)
16、GridView合并表头多重表头无错完美版(以合并3列3行举例)
17、GridView突出显示某一单元格(例如金额低于多少,分数不及格等)
18、GridView加入自动求和求平均值小计
19、GridView数据导入Excel/Excel数据读入GridView
--------------------------------
正文
--------------------------------
1.GridView简单代码分页排序:
1.AllowSorting设为True,aspx代码中是AllowSorting="True";
2.默认1页10条,如果要修改每页条数,修改PageSize即可,在aspx代码中是PageSize="12"。
3.默认的是单向排序的,右击GridView弹出“属性”,选择AllowSorting为True即可。
4.添加代码:
1 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) 2 3 { 4 5 GridView1.PageIndex = e.NewPageIndex; 6 7 Bind(); 8 9 }
2.GridView选中,编辑,取消,删除:
后台代码:
1 using System; 2 3 using System.Data; 4 5 using System.Configuration; 6 7 using System.Web; 8 9 using System.Web.Security; 10 11 using System.Web.UI; 12 13 using System.Web.UI.WebControls; 14 15 using System.Web.UI.WebControls.WebParts; 16 17 using System.Web.UI.HtmlControls; 18 19 using System.Data.SqlClient; 20 21 public partial class _Default : System.Web.UI.Page 22 23 { 24 25 SqlConnection sqlcon; 26 27 SqlCommand sqlcom; 28 29 string strCon = "Data Source=(local);Database=数据库名;Uid=帐号;Pwd=密码"; 30 31 protected void Page_Load(object sender, EventArgs e) 32 33 { 34 35 if (!IsPostBack) 36 37 { 38 39 bind(); 40 41 } 42 43 } 44 45 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) 46 47 { 48 49 GridView1.EditIndex = e.NewEditIndex; 50 51 bind(); 52 53 } 54 55 //删除 56 57 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 58 59 { 60 61 string sqlstr = "delete from 表 where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'"; 62 63 sqlcon = new SqlConnection(strCon); 64 65 sqlcom = new SqlCommand(sqlstr,sqlcon); 66 67 sqlcon.Open(); 68 69 sqlcom.ExecuteNonQuery(); 70 71 sqlcon.Close(); 72 73 bind(); 74 75 } 76 77 //更新 78 79 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 80 81 { 82 83 sqlcon = new SqlConnection(strCon); 84 85 string sqlstr = "update 表 set 字段1='" 86 87 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',字段2='" 88 89 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',字段3='" 90 91 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where id='" 92 93 + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'"; 94 95 sqlcom=new SqlCommand(sqlstr,sqlcon); 96 97 sqlcon.Open(); 98 99 sqlcom.ExecuteNonQuery(); 100 101 sqlcon.Close(); 102 103 GridView1.EditIndex = -1; 104 105 bind(); 106 107 } 108 109 //取消 110 111 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) 112 113 { 114 115 GridView1.EditIndex = -1; 116 117 bind(); 118 119 } 120 121 //绑定 122 123 public void bind() 124 125 { 126 127 string sqlstr = "select * from 表"; 128 129 sqlcon = new SqlConnection(strCon); 130 131 SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); 132 133 DataSet myds = new DataSet(); 134 135 sqlcon.Open(); 136 137 myda.Fill(myds, "表"); 138 139 GridView1.DataSource = myds; 140 141 GridView1.DataKeyNames = new string[] { "id" };//主键 142 143 GridView1.DataBind(); 144 145 sqlcon.Close(); 146 147 } 148 149 }
前台主要代码:
... ...
1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" 2 3 ForeColor="#333333" GridLines="None" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" 4 5 OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit"> 6 7 <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> 8 9 <Columns> 10 11 <asp:BoundField DataField="身份证号码" HeaderText="用户ID" ReadOnly="True" /> 12 13 <asp:BoundField DataField="姓名" HeaderText="用户姓名" /> 14 15 <asp:BoundField DataField="员工性别" HeaderText="性别" /> 16 17 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /> 18 19 <asp:CommandField HeaderText="选择" ShowSelectButton="True" /> 20 21 <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> 22 23 <asp:CommandField HeaderText="删除" ShowDeleteButton="True" /> 24 25 </Columns> 26 27 <RowStyle ForeColor="#000066" /> 28 29 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 30 31 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> 32 33 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 34 35 </asp:GridView>
3.GridView正反双向排序:
后台代码:
1 using System; 2 3 using System.Data; 4 5 using System.Configuration; 6 7 using System.Collections; 8 9 using System.Web; 10 11 using System.Web.Security; 12 13 using System.Web.UI; 14 15 using System.Web.UI.WebControls; 16 17 using System.Web.UI.WebControls.WebParts; 18 19 using System.Web.UI.HtmlControls; 20 21 using System.Data.SqlClient; 22 23 public partial class Default3 : System.Web.UI.Page 24 25 { SqlConnection sqlcon; 26 27 string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd="; 28 29 protected void Page_Load(object sender, EventArgs e) 30 31 { 32 33 if (!IsPostBack) 34 35 { 36 37 ViewState["SortOrder"] = "身份证号码"; 38 39 ViewState["OrderDire"] = "ASC"; 40 41 bind(); 42 43 } 44 45 } 46 47 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) 48 49 { 50 51 string sPage = e.SortExpression; 52 53 if (ViewState["SortOrder"].ToString() == sPage) 54 55 { 56 57 if (ViewState["OrderDire"].ToString() == "Desc") 58 59 ViewState["OrderDire"] = "ASC"; 60 61 else 62 63 ViewState["OrderDire"] = "Desc"; 64 65 } 66 67 else 68 69 { 70 71 ViewState["SortOrder"] = e.SortExpression; 72 73 } 74 75 bind(); 76 77 } 78 79 public void bind() 80 81 { 82 83 84 85 string sqlstr = "select top 5 * from 飞狐工作室"; 86 87 sqlcon = new SqlConnection(strCon); 88 89 SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); 90 91 DataSet myds = new DataSet(); 92 93 sqlcon.Open(); 94 95 myda.Fill(myds, "飞狐工作室"); 96 97 DataView view = myds.Tables["飞狐工作室"].DefaultView; 98 99 string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"]; 100 101 view.Sort = sort; 102 103 GridView1.DataSource = view; 104 105 GridView1.DataBind(); 106 107 sqlcon.Close(); 108 109 } 110 111 }
前台主要代码:
1 <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" 2 3 CellPadding="3" Font-Size="12px" OnSorting="GridView1_Sorting" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"> 4 5 <FooterStyle BackColor="White" ForeColor="#000066" /> 6 7 <Columns> 8 9 <asp:BoundField DataField="身份证号码" HeaderText="用户ID" SortExpression="身份证号码" /> 10 11 <asp:BoundField DataField="姓名" HeaderText="用户姓名" SortExpression="姓名"/> 12 13 <asp:BoundField DataField="员工性别" HeaderText="性别" SortExpression="员工性别"/> 14 15 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址"/> 16 17 </Columns> 18 19 <RowStyle ForeColor="#000066" /> 20 21 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 22 23 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> 24 25 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 26 27 </asp:GridView>
4.GridView和下拉菜单DropDownList结合:
后台代码:
1 using System; 2 3 using System.Data; 4 5 using System.Configuration; 6 7 using System.Collections; 8 9 using System.Web; 10 11 using System.Web.Security; 12 13 using System.Web.UI; 14 15 using System.Web.UI.WebControls; 16 17 using System.Web.UI.WebControls.WebParts; 18 19 using System.Web.UI.HtmlControls; 20 21 using System.Data.SqlClient; 22 23 public partial class Default4 : System.Web.UI.Page 24 25 { 26 27 SqlConnection sqlcon; 28 29 string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa"; 30 31 protected void Page_Load(object sender, EventArgs e) 32 33 { 34 35 DropDownList ddl; 36 37 if (!IsPostBack) 38 39 { 40 41 string sqlstr = "select top 5 * from 飞狐工作室"; 42 43 sqlcon = new SqlConnection(strCon); 44 45 SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); 46 47 DataSet myds = new DataSet(); 48 49 sqlcon.Open(); 50 51 myda.Fill(myds, "飞狐工作室"); 52 53 GridView1.DataSource = myds; 54 55 GridView1.DataBind(); 56 57 for (int i = 0; i <= GridView1.Rows.Count - 1; i++) 58 59 { 60 61 DataRowView mydrv = myds.Tables["飞狐工作室"].DefaultView[i]; 62 63 if (Convert.ToString(mydrv["员工性别"]).Trim() == "True") 64 65 { 66 67 ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1"); 68 69 ddl.SelectedIndex = 0; 70 71 } 72 73 if (Convert.ToString(mydrv["员工性别"]).Trim() == "False") 74 75 { 76 77 ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1"); 78 79 ddl.SelectedIndex = 1; 80 81 } 82 83 } 84 85 sqlcon.Close(); 86 87 } 88 89 } 90 91 public SqlDataReader ddlbind() 92 93 { 94 95 string sqlstr = "select distinct 员工性别 from 飞狐工作室"; 96 97 sqlcon = new SqlConnection(strCon); 98 99 SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon); 100 101 sqlcon.Open(); 102 103 return sqlcom.ExecuteReader(); 104 105 }
前台主要代码:
1 <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" 2 3 CellPadding="3" Font-Size="12px" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"> 4 5 <FooterStyle BackColor="White" ForeColor="#000066" /> 6 7 <Columns> 8 9 <asp:BoundField DataField="身份证号码" HeaderText="用户ID" SortExpression="身份证号码" /> 10 11 <asp:BoundField DataField="姓名" HeaderText="用户姓名" SortExpression="姓名"/> 12 13 <asp:TemplateField HeaderText="员工性别"> 14 15 <ItemTemplate> 16 17 <asp:DropDownList ID="DropDownList1" runat="server" DataSource='<%# ddlbind()%>' DataValueField="员工性别" DataTextField="员工性别"> 18 19 </asp:DropDownList> 20 21 </ItemTemplate> 22 23 </asp:TemplateField> 24 25 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址"/> 26 27 28 29 </Columns> 30 31 <RowStyle ForeColor="#000066" /> 32 33 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 34 35 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> 36 37 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 38 39 </asp:GridView>
5.GridView和CheckBox结合:
后台代码:
1 using System; 2 3 using System.Data; 4 5 using System.Configuration; 6 7 using System.Web; 8 9 using System.Web.Security; 10 11 using System.Web.UI; 12 13 using System.Web.UI.WebControls; 14 15 using System.Web.UI.WebControls.WebParts; 16 17 using System.Web.UI.HtmlControls; 18 19 using System.Data.SqlClient; 20 21 public partial class Default5 : System.Web.UI.Page 22 23 { 24 25 SqlConnection sqlcon; 26 27 string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa"; 28 29 protected void Page_Load(object sender, EventArgs e) 30 31 { 32 33 if (!IsPostBack) 34 35 { 36 37 bind(); 38 39 } 40 41 } 42 43 protected void CheckBox2_CheckedChanged(object sender, EventArgs e) 44 45 { 46 47 for (int i = 0; i <= GridView1.Rows.Count - 1; i++) 48 49 { 50 51 CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); 52 53 if (CheckBox2.Checked == true) 54 55 { 56 57 cbox.Checked = true; 58 59 } 60 61 else 62 63 { 64 65 cbox.Checked = false; 66 67 } 68 69 } 70 71 } 72 73 protected void Button2_Click(object sender, EventArgs e) 74 75 { 76 77 sqlcon = new SqlConnection(strCon); 78 79 SqlCommand sqlcom; 80 81 for (int i = 0; i <= GridView1.Rows.Count - 1; i++) 82 83 { 84 85 CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); 86 87 if (cbox.Checked == true) 88 89 { 90 91 string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[i].Value + "'"; 92 93 sqlcom = new SqlCommand(sqlstr, sqlcon); 94 95 sqlcon.Open(); 96 97 sqlcom.ExecuteNonQuery(); 98 99 sqlcon.Close(); 100 101 } 102 103 } 104 105 bind(); 106 107 } 108 109 protected void Button1_Click(object sender, EventArgs e) 110 111 { 112 113 CheckBox2.Checked = false; 114 115 for (int i = 0; i <= GridView1.Rows.Count - 1; i++) 116 117 { 118 119 CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); 120 121 cbox.Checked = false; 122 123 } 124 125 } 126 127 public void bind() 128 129 { 130 131 string sqlstr = "select top 5 * from 飞狐工作室"; 132 133 sqlcon = new SqlConnection(strCon); 134 135 SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); 136 137 DataSet myds = new DataSet(); 138 139 sqlcon.Open(); 140 141 myda.Fill(myds, "tb_Member"); 142 143 GridView1.DataSource = myds; 144 145 GridView1.DataKeyNames = new string[] { "身份证号码" }; 146 147 GridView1.DataBind(); 148 149 sqlcon.Close(); 150 151 } 152 153 }
前台主要代码:
1 <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" 2 3 CellPadding="3" Font-Size="12px" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"> 4 5 <FooterStyle BackColor="White" ForeColor="#000066" /> 6 7 <Columns> 8 9 <asp:TemplateField> 10 11 <ItemTemplate> 12 13 <asp:CheckBox ID="CheckBox1" runat="server" /> 14 15 </ItemTemplate> 16 17 </asp:TemplateField> 18 19 <asp:BoundField DataField="身份证号码" HeaderText="用户ID" SortExpression="身份证号码" /> 20 21 <asp:BoundField DataField="姓名" HeaderText="用户姓名" SortExpression="姓名"/> 22 23 24 25 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址"/> 26 27 28 29 </Columns> 30 31 <RowStyle ForeColor="#000066" /> 32 33 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 34 35 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> 36 37 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 38 39 </asp:GridView> 40 41 <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" Font-Size="12px" OnCheckedChanged="CheckBox2_CheckedChanged" 42 43 Text="全选" /> 44 45 <asp:Button ID="Button1" runat="server" Font-Size="12px" Text="取消" OnClick="Button1_Click" /> 46 47 <asp:Button ID="Button2" runat="server" Font-Size="12px" Text="删除" OnClick="Button2_Click" />
6.鼠标移到GridView某一行时改变该行的背景色方法一:
做法:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:
1 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 2 3 { 4 5 //首先判断是否是数据行 6 7 if (e.Row.RowType == DataControlRowType.DataRow) 8 9 { 10 11 //当鼠标停留时更改背景色 12 13 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'"); 14 15 //当鼠标移开时还原背景色 16 17 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); 18 19 } 20 21 }
前台代码:
1 <html xmlns="http://www.w3.org/1999/xhtml" > 2 3 <head runat="server"> 4 5 <title>实现鼠标划过改变GridView的行背景色清清月儿http://blog.csdn.net/21aspnet </title> 6 7 </head> 8 9 <body> 10 11 <form id="form1" runat="server"> 12 13 <div> 14 15 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="身份证号码" 16 17 DataSourceID="SqlDataSource1" AllowSorting="True" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound"> 18 19 <Columns> 20 21 <asp:BoundField DataField="身份证号码" HeaderText="身份证号码" ReadOnly="True" SortExpression="身份证号码" /> 22 23 <asp:BoundField DataField="姓名" HeaderText="姓名" SortExpression="姓名" /> 24 25 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址" /> 26 27 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" /> 28 29 </Columns> 30 31 <FooterStyle BackColor="White" ForeColor="#000066" /> 32 33 <RowStyle ForeColor="#000066" /> 34 35 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 36 37 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> 38 39 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 40 41 </asp:GridView> 42 43 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:北风贸易ConnectionString1 %>" 44 45 SelectCommand="SELECT top 5 [身份证号码], [姓名], [员工性别], [家庭住址], [邮政编码] FROM [飞狐工作室]" DataSourceMode="DataReader"></asp:SqlDataSource> 46 47 48 49 </div> 50 51 </form> 52 53 </body> 54 55 </html> 56 57
7.鼠标移到GridView某一行时改变该行的背景色方法二:
做法:和上面的一样就是代码不同
1 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 2 3 { 4 5 //如果是绑定数据行 6 7 if (e.Row.RowType == DataControlRowType.DataRow) 8 9 { 10 11 //鼠标经过时,行背景色变 12 13 e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'"); 14 15 //鼠标移出时,行背景色变 16 17 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'"); 18 19 } 20 21 }
8.GridView实现删除时弹出确认对话框:
实现方法:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:
1 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 2 3 { 4 5 //如果是绑定数据行 6 7 if (e.Row.RowType == DataControlRowType.DataRow) 8 9 { 10 11 if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate) 12 13 { 14 15 ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:/"" + e.Row.Cells[1].Text + "/"吗?')"); 16 17 } 18 19 } 20 21 }
9.GridView实现自动编号:
实现方法:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:
1 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 2 3 { 4 5 if (e.Row.RowIndex != -1) 6 7 { 8 9 int id = e.Row.RowIndex + 1; 10 11 e.Row.Cells[0].Text = id.ToString(); 12 13 } 14 15 }
注意这时最好把前台的第一列的表头该为“编号”,因为以前的第一列被“吃掉”了。
1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" 2 3 OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound"> 4 5 <FooterStyle BackColor="White" ForeColor="#000066" /> 6 7 <Columns> 8 9 <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" /> 10 11 <asp:BoundField DataField="姓名" HeaderText="用户姓名" /> 12 13 <asp:BoundField DataField="员工性别" HeaderText="性别" /> 14 15 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /> 16 17 <asp:CommandField HeaderText="选择" ShowSelectButton="True" /> 18 19 <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> 20 21 <asp:CommandField HeaderText="删除" ShowDeleteButton="True" /> 22 23 </Columns> 24 25 <RowStyle ForeColor="#000066" /> 26 27 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 28 29 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> 30 31 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 32 33 </asp:GridView>
10.GridView实现自定义时间货币等字符串格式:
解决方法:
在asp.net 2.0中,如果要在绑定列中显示比如日期格式等,如果用下面的方法是显示不了的
1 <asp :BoundField DataField="CreationDate" 2 3 DataFormatString="{0:M-dd-yyyy}" 4 5 HeaderText="CreationDate" />
主要是由于htmlencode属性默认设置为true,已防止XSS攻击,安全起见而用的,所以,可以有以下两种方法解决
1、
1 <asp :GridView ID="GridView1" runat="server"> 2 3 <columns> 4 5 <asp :BoundField DataField="CreationDate" 6 7 DataFormatString="{0:M-dd-yyyy}" 8 9 HtmlEncode="false" 10 11 HeaderText="CreationDate" /> 12 13 </columns> 14 15 </asp>
将htmlencode设置为false即可
另外的解决方法为,使用模版列
1 <asp :GridView ID="GridView3" runat="server" > 2 3 <columns> 4 5 <asp :TemplateField HeaderText="CreationDate" > 6 7 <edititemtemplate> 8 9 <asp :Label ID="Label1" runat="server" 10 11 Text='<%# Eval("CreationDate", "{0:M-dd-yyyy}") %>'> 12 13 </asp> 14 15 </edititemtemplate> 16 17 <itemtemplate> 18 19 <asp :Label ID="Label1" runat="server" 20 21 Text=’<%# Bind("CreationDate", "{0:M-dd-yyyy}") %>'> 22 23 </asp> 24 25 </itemtemplate> 26 27 </asp> 28 29 </columns> 30 31 </asp>
前台代码:
<
1 asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="身份证号码" 2 3 DataSourceID="SqlDataSource1" AllowSorting="True" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound"> 4 5 <Columns> 6 7 <asp:BoundField DataField="身份证号码" HeaderText="身份证号码" ReadOnly="True" SortExpression="身份证号码" /> 8 9 <asp:BoundField DataField="姓名" HeaderText="姓名" SortExpression="姓名" /> 10 11 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" /> 12 13 <asp:BoundField DataField="出生日期" HeaderText="出生日期" SortExpression="出生日期" /> 14 15 <asp:BoundField DataField="起薪" HeaderText="起薪" SortExpression="起薪" /> 16 17 </Columns> 18 19 <FooterStyle BackColor="White" ForeColor="#000066" /> 20 21 <RowStyle ForeColor="#000066" /> 22 23 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 24 25 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> 26 27 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 28 29 </asp:GridView> 30 31 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:北风贸易ConnectionString1 %>" 32 33 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实现用“...”代替超长字符串:
解决方法:数据绑定后过滤每一行即可
1 for (int i = 0; i <= GridView1.Rows.Count - 1; i++) 2 3 { 4 5 DataRowView mydrv; 6 7 string gIntro; 8 9 if (GridView1.PageIndex == 0) 10 11 { 12 13 mydrv = myds.Tables["飞狐工作室"].DefaultView[i];//表名 14 15 gIntro = Convert.ToString(mydrv["家庭住址"]);//所要处理的字段 16 17 GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2); 18 19 } 20 21 else 22 23 { 24 25 mydrv = myds.Tables["飞狐工作室"].DefaultView[i + (5 * GridView1.PageIndex)]; 26 27 gIntro = Convert.ToString(mydrv["家庭住址"]); 28 29 GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2); 30 31 } 32 33 }
调用的方法:
1 public string SubStr(string sString, int nLeng) 2 3 { 4 5 if (sString.Length <= nLeng) 6 7 { 8 9 return sString; 10 11 } 12 13 string sNewStr = sString.Substring(0, nLeng); 14 15 sNewStr = sNewStr + "..."; 16 17 return sNewStr; 18 19 }
12.GridView一般换行与强制换行:
首先设置<asp:BoundField DataField="家庭住址" HeaderText="家庭住址" ItemStyle-Width="100" />gridview里有一列绑定的数据很长,显示的时候在一行里面显示,页面拉得很宽。原因是连续英文段为一个整体导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add("word-break", "break-all")就可以。如果要给所有的列增加此属性:
1 protected void Page_Load(object sender, EventArgs e) 2 3 { 4 5 //正常换行 6 7 GridView1.Attributes.Add("style", "word-break:keep-all;word-wrap:normal"); 8 9 //下面这行是自动换行 10 11 GridView1.Attributes.Add("style", "word-break:break-all;word-wrap:break-word"); 12 13 if (!IsPostBack) 14 15 { 16 17 bind();//调用数据绑定即可 18 19 } 20 21 }
总之:善用CSS的word-break:break-all;word-wrap:break-word属性即可,这个属性是通用的对于顽固的南换行问题都可以解决,不局限于GridView。
13.GridView显示隐藏某一列:
解决方案:
1 public void bind() 2 3 { 4 5 string sqlstr = "select top 5 * from 飞狐工作室"; 6 7 sqlcon = new SqlConnection(strCon); 8 9 SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); 10 11 DataSet myds = new DataSet(); 12 13 sqlcon.Open(); 14 15 myda.Fill(myds, "飞狐工作室"); 16 17 GridView1.DataSource = myds; 18 19 GridView1.DataKeyNames = new string[] { "身份证号码" }; 20 21 GridView1.DataBind(); 22 23 sqlcon.Close(); 24 25 GridView1.Columns[3].Visible = false;//一开始隐藏 26 27 CheckBox1.Checked = false;//如果不这样后面的代码会把他True 28 29 }
双击CheckBox1,在CheckedChanged方法里写上代码,最后代码如下:
1 protected void CheckBox1_CheckedChanged(object sender, EventArgs e) 2 3 { 4 5 GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible; 6 7 Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString()); 8 9 }
注意:CheckBox1的AutoPostBack要True!
14.GridView弹出新页面:
1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" 2 3 OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" > 4 5 <FooterStyle BackColor="White" ForeColor="#000066" /> 6 7 <Columns> 8 9 <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" /> 10 11 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" /> 12 13 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /> 14 15 <asp:HyperLinkField HeaderText="姓名" Text="姓名" DataNavigateUrlFields="姓名" DataNavigateUrlFormatString="Default6.aspx?GoodsID={0}" Target="mainframe" NavigateUrl="~/Default6.aspx" DataTextField="姓名" > 16 17 </asp:HyperLinkField> 18 19 <asp:CommandField HeaderText="选择" ShowSelectButton="True" /> 20 21 <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> 22 23 <asp:CommandField HeaderText="删除" ShowDeleteButton="True" /> 24 25 </Columns> 26 27 <RowStyle ForeColor="#000066" /> 28 29 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 30 31 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" /> 32 33 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 34 35 </asp:GridView>
DataNavigateUrlFields是链接的字段名,DataNavigateUrlFormatString是路径。
15.GridView固定表头(不用javascript只用CSS!,很好用):
代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>GridView固定表头 清清月儿http://blog.csdn.net/21aspnet </title> <style> .Freezing { position:relative ; table-layout:fixed; top:expression(this.offsetParent.scrollTop); z-index: 10; } .Freezing th{text-overflow:ellipsis;overflow:hidden;white-space: nowrap;padding:2px;} </style> </head> <body style="font-size=12px"> <form id="form1" runat="server"> <div style="overflow-y: scroll; height: 200px;width:300px" id="dvBody"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowCreated="GridView1_RowCreated" > <FooterStyle BackColor="White" ForeColor="#000066" /> <Columns> <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" /> <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" /> <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /> <asp:BoundField DataField="姓名" HeaderText="姓名" /> </Columns> <RowStyle ForeColor="#000066" /> <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/> <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" CssClass="Freezing"/> </asp:GridView> </div> </form> </body> </html>
用法:CSS设如上的样式,HeaderStyle加CssClass="Freezing,套住GridView的Div设置高度宽度 <div style="overflow-y: scroll; height: 200px;width:200px" >
16.GridView合并表头多重表头无错完美版(以合并3列3行举例)
后台代码:
1 protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) 2 3 { 4 5 switch (e.Row.RowType) 6 7 { 8 9 case DataControlRowType.Header: 10 11 //第一行表头 12 13 TableCellCollection tcHeader = e.Row.Cells; 14 15 tcHeader.Clear(); 16 17 tcHeader.Add(new TableHeaderCell()); 18 19 tcHeader[0].Attributes.Add("rowspan", "3"); //跨Row 20 21 tcHeader[0].Attributes.Add("bgcolor", "white"); 22 23 tcHeader[0].Text = ""; 24 25 tcHeader.Add(new TableHeaderCell()); 26 27 //tcHeader[1].Attributes.Add("bgcolor", "Red"); 28 29 tcHeader[1].Attributes.Add("colspan", "6"); //跨Column 30 31 tcHeader[1].Text = "全部信息</th></tr><tr>"; 32 33 //第二行表头 34 35 tcHeader.Add(new TableHeaderCell()); 36 37 tcHeader[2].Attributes.Add("bgcolor", "DarkSeaGreen"); 38 39 tcHeader[2].Text = "身份证号码"; 40 41 tcHeader.Add(new TableHeaderCell()); 42 43 tcHeader[3].Attributes.Add("bgcolor", "LightSteelBlue"); 44 45 tcHeader[3].Attributes.Add("colspan", "2"); 46 47 tcHeader[3].Text = "基本信息"; 48 49 tcHeader.Add(new TableHeaderCell()); 50 51 tcHeader[4].Attributes.Add("bgcolor", "DarkSeaGreen"); 52 53 tcHeader[4].Text = "福利"; 54 55 tcHeader.Add(new TableHeaderCell()); 56 57 tcHeader[5].Attributes.Add("bgcolor", "LightSteelBlue"); 58 59 tcHeader[5].Attributes.Add("colspan", "2"); 60 61 tcHeader[5].Text = "联系方式</th></tr><tr>"; 62 63 //第三行表头 64 65 tcHeader.Add(new TableHeaderCell()); 66 67 tcHeader[6].Attributes.Add("bgcolor", "Khaki"); 68 69 tcHeader[6].Text = "身份证号码"; 70 71 tcHeader.Add(new TableHeaderCell()); 72 73 tcHeader[7].Attributes.Add("bgcolor", "Khaki"); 74 75 tcHeader[7].Text = "姓名"; 76 77 tcHeader.Add(new TableHeaderCell()); 78 79 tcHeader[8].Attributes.Add("bgcolor", "Khaki"); 80 81 tcHeader[8].Text = "出生日期"; 82 83 tcHeader.Add(new TableHeaderCell()); 84 85 tcHeader[9].Attributes.Add("bgcolor", "Khaki"); 86 87 tcHeader[9].Text = "薪水"; 88 89 tcHeader.Add(new TableHeaderCell()); 90 91 tcHeader[10].Attributes.Add("bgcolor", "Khaki"); 92 93 tcHeader[10].Text = "家庭住址"; 94 95 tcHeader.Add(new TableHeaderCell()); 96 97 tcHeader[11].Attributes.Add("bgcolor", "Khaki"); 98 99 tcHeader[11].Text = "邮政编码"; 100 101 break; 102 103 } 104 105 } 106 107 }
前台:
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 5 <head runat="server"> 6 7 <title>GridView合并多重表头表头 清清月儿http://blog.csdn.net/21aspnet </title> 8 9 </head> 10 11 <body > 12 13 <form id="form1" runat="server"> 14 15 <div > 16 17 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowEditing="GridView1_RowEditing" 18 19 OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowCreated="GridView1_RowCreated" > 20 21 <FooterStyle BackColor="White" ForeColor="#000066" /> 22 23 <Columns> 24 25 <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> 26 27 <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" /> 28 29 <asp:BoundField DataField="姓名" HeaderText="姓名" /> 30 31 <asp:BoundField DataField="出生日期" HeaderText="邮政编码" /> 32 33 <asp:BoundField DataField="起薪" HeaderText="起薪" /> 34 35 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /> 36 37 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" /> 38 39 40 41 </Columns> 42 43 <RowStyle ForeColor="#000066" /> 44 45 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 46 47 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/> 48 49 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 50 51 </asp:GridView> 52 53 </div> 54 55 </form> 56 57 </body> 58 59 </html>
17.GridView突出显示某一单元格(例如金额低于多少,分数不及格等)
解决方案:主要是绑定后过滤
1 GridView1.DataBind(); 2 3 for (int i = 0; i <= GridView1.Rows.Count - 1; i++) 4 5 { 6 7 DataRowView mydrv = myds.Tables["飞狐工作室"].DefaultView[i]; 8 9 string score = Convert.ToString(mydrv["起薪"]); 10 11 if (Convert.ToDouble(score) < 34297.00)//大家这里根据具体情况设置可能ToInt32等等 12 13 { 14 15 GridView1.Rows[i].Cells[4].BackColor = System.Drawing.Color.Red; 16 17 } 18 19 } 20 21 sqlcon.Close();
前台代码:
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 5 <head id="Head1" runat="server"> 6 7 <title>GridView突出显示某一单元格 清清月儿http://blog.csdn.net/21aspnet </title> 8 9 </head> 10 11 <body > 12 13 <form id="form1" runat="server"> 14 15 <div > 16 17 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowEditing="GridView1_RowEditing" 18 19 OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" > 20 21 <FooterStyle BackColor="White" ForeColor="#000066" /> 22 23 <Columns> 24 25 <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> 26 27 <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" /> 28 29 <asp:BoundField DataField="姓名" HeaderText="姓名" /> 30 31 <asp:BoundField DataField="出生日期" HeaderText="邮政编码" /> 32 33 <asp:BoundField DataField="起薪" HeaderText="起薪" DataFormatString="{0:C}" HtmlEncode="false"/> 34 35 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /> 36 37 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" /> 38 39 40 41 </Columns> 42 43 <RowStyle ForeColor="#000066" /> 44 45 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 46 47 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/> 48 49 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 50 51 </asp:GridView> 52 53 </div> 54 55 </form> 56 57 </body> 58 59 </html>
18.GridView加入自动求和求平均值小计
解决方案:
1 private double sum = 0;//取指定列的数据和,你要根据具体情况对待可能你要处理的是int 2 3 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 4 5 { 6 7 8 9 if (e.Row.RowIndex >= 0) 10 11 { 12 13 sum += Convert.ToDouble(e.Row.Cells[6].Text); 14 15 } 16 17 else if (e.Row.RowType == DataControlRowType.Footer) 18 19 { 20 21 e.Row.Cells[5].Text = "总薪水为:"; 22 23 e.Row.Cells[6].Text = sum.ToString(); 24 25 e.Row.Cells[3].Text = "平均薪水为:"; 26 27 e.Row.Cells[4].Text = ((int)(sum / GridView1.Rows.Count)).ToString(); 28 29 30 31 } 32 33 }
前台:唯一的花头就是设置ShowFooter="True" ,否则默认表头为隐藏的!
1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowEditing="GridView1_RowEditing" 2 3 OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowDataBound="GridView1_RowDataBound" ShowFooter="True" > 4 5 <FooterStyle BackColor="White" ForeColor="#000066" /> 6 7 <Columns> 8 9 <asp:CommandField HeaderText="编辑" ShowEditButton="True" /> 10 11 <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" /> 12 13 <asp:BoundField DataField="姓名" HeaderText="姓名" /> 14 15 <asp:BoundField DataField="出生日期" HeaderText="邮政编码" /> 16 17 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /> 18 19 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" /> 20 21 <asp:BoundField DataField="起薪" HeaderText="起薪" /> 22 23 24 25 </Columns> 26 27 <RowStyle ForeColor="#000066" /> 28 29 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 30 31 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/> 32 33 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 34 35 </asp:GridView>
19.GridView数据导入Excel/Excel数据读入GridView
解决方案:
页面增加一个按钮,单击事件添加如下方法:
1 protected void Button1_Click(object sender, EventArgs e) 2 3 { 4 5 Export("application/ms-excel", "学生成绩报表.xls"); 6 7 } 8 9 private void Export(string FileType, string FileName) 10 11 { 12 13 Response.Charset = "GB2312"; 14 15 Response.ContentEncoding = System.Text.Encoding.UTF7; 16 17 Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString()); 18 19 Response.ContentType = FileType; 20 21 this.EnableViewState = false; 22 23 StringWriter tw = new StringWriter(); 24 25 HtmlTextWriter hw = new HtmlTextWriter(tw); 26 27 GridView1.RenderControl(hw); 28 29 Response.Write(tw.ToString()); 30 31 Response.End(); 32 33 } 34 35 //如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内 36 37 public override void VerifyRenderingInServerForm(Control control) 38 39 { 40 41 }
还有由于是文件操作所以要引入名称空间IO和Text
后台代码:
1 using System; 2 3 using System.Data; 4 5 using System.Configuration; 6 7 using System.Web; 8 9 using System.Web.Security; 10 11 using System.Web.UI; 12 13 using System.Web.UI.WebControls; 14 15 using System.Web.UI.WebControls.WebParts; 16 17 using System.Web.UI.HtmlControls; 18 19 using System.Data.SqlClient; 20 21 using System.Drawing; 22 23 using System.IO; 24 25 using System.Text; 26 27 public partial class Default7 : System.Web.UI.Page 28 29 { 30 31 SqlConnection sqlcon; 32 33 SqlCommand sqlcom; 34 35 string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa"; 36 37 protected void Page_Load(object sender, EventArgs e) 38 39 { 40 41 if (!IsPostBack) 42 43 { 44 45 bind(); 46 47 } 48 49 } 50 51 52 53 public void bind() 54 55 { 56 57 string sqlstr = "select top 5 * from 飞狐工作室"; 58 59 sqlcon = new SqlConnection(strCon); 60 61 SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); 62 63 DataSet myds = new DataSet(); 64 65 sqlcon.Open(); 66 67 myda.Fill(myds, "飞狐工作室"); 68 69 GridView1.DataSource = myds; 70 71 GridView1.DataKeyNames = new string[] { "身份证号码" }; 72 73 GridView1.DataBind(); 74 75 sqlcon.Close(); 76 77 } 78 79 protected void Button1_Click(object sender, EventArgs e) 80 81 { 82 83 Export("application/ms-excel", "学生成绩报表.xls"); 84 85 } 86 87 private void Export(string FileType, string FileName) 88 89 { 90 91 Response.Charset = "GB2312"; 92 93 Response.ContentEncoding = System.Text.Encoding.UTF7; 94 95 Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString()); 96 97 Response.ContentType = FileType; 98 99 this.EnableViewState = false; 100 101 StringWriter tw = new StringWriter(); 102 103 HtmlTextWriter hw = new HtmlTextWriter(tw); 104 105 GridView1.RenderControl(hw); 106 107 Response.Write(tw.ToString()); 108 109 Response.End(); 110 111 } 112 113 public override void VerifyRenderingInServerForm(Control control) 114 115 { 116 117 } 118 119 120 121 }
前台:
1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" 2 3 BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" > 4 5 <FooterStyle BackColor="White" ForeColor="#000066" /> 6 7 <Columns> 8 9 <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" /> 10 11 <asp:BoundField DataField="姓名" HeaderText="姓名" /> 12 13 <asp:BoundField DataField="出生日期" HeaderText="邮政编码" /> 14 15 <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /> 16 17 <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" /> 18 19 <asp:BoundField DataField="起薪" HeaderText="起薪" /> 20 21 22 23 </Columns> 24 25 <RowStyle ForeColor="#000066" /> 26 27 <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /> 28 29 <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/> 30 31 <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /> 32 33 </asp:GridView> 34 35 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出" />
读取Excel数据的代码:这个很简单的
1 private DataSet CreateDataSource() 2 3 { 4 5 string strCon; 6 7 strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("excel.xls") + "; Extended Properties=Excel 8.0;"; 8 9 OleDbConnection olecon = new OleDbConnection(strCon); 10 11 OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strCon); 12 13 DataSet myds = new DataSet(); 14 15 myda.Fill(myds); 16 17 return myds; 18 19 } 20 21 protected void Button1_Click(object sender, EventArgs e) 22 23 { 24 25 GridView1.DataSource = CreateDataSource(); 26 27 GridView1.DataBind(); 28 29 }