找回密码
 会员注册
查看: 127|回复: 0

Asp.net中GridView使用详解

[复制链接]

1389

主题

5

回帖

496万

积分

管理员

积分
4962990
发表于 2024-2-29 08:36:51 | 显示全部楼层 |阅读模式

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.添加代码:

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


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

后台代码:


  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. }
复制代码

前台主要代码:

  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正反双向排序:


后台代码:

  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. string sqlstr = "select top 5 * from 飞狐工作室";
  43. sqlcon = new SqlConnection(strCon);
  44. SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
  45. DataSet myds = new DataSet();
  46. sqlcon.Open();
  47. myda.Fill(myds, "飞狐工作室");
  48. DataView view = myds.Tables["飞狐工作室"].DefaultView;
  49. string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
  50. view.Sort = sort;
  51. GridView1.DataSource = view;
  52. GridView1.DataBind();
  53. sqlcon.Close();
  54. }
  55. }
复制代码

前台主要代码:

  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结合:


后台代码:

  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. }
复制代码

前台主要代码:

  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. </Columns>
  15. <RowStyle ForeColor="#000066" />
  16. <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
  17. <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
  18. <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
  19. </asp:GridView>
复制代码

5.GridView和CheckBox结合:


后台代码:

  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. }
复制代码
前台主要代码:

  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. <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址"/>
  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>
  19. <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" Font-Size="9pt" OnCheckedChanged="CheckBox2_CheckedChanged"
  20. Text="全选" />
  21. <asp:Button ID="Button1" runat="server" Font-Size="9pt" Text="取消" OnClick="Button1_Click" />
  22. <asp:Button ID="Button2" runat="server" Font-Size="9pt" Text="删除" OnClick="Button2_Click" />
复制代码

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


做法:

双击GridView的OnRowDataBound事件;

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

  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. }
复制代码

前台代码:

  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. </div>
  25. </form>
  26. </body>
  27. </html>
复制代码

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


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

  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()方法添加代码,最后代码如下所示:

  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()方法添加代码,最后代码如下所示:

  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. }
复制代码

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

  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中,如果要在绑定列中显示比如日期格式等,如果用下面的方法是显示不了的

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

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

1、

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

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

  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>
复制代码


前台代码:

  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}  货币;

{04}由0填充的4个字符宽的字段中显示整数;

{0:000.0}四舍五入小数点保留第几位有效数字;

{0:N2}小数点保留2位有效数字;{0:N2}%   小数点保留2位有效数字加百分号;

{0}长日期;{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. 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. }
复制代码

调用的方法:

  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一般换行与强制换行:


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

  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显示隐藏某一列:



解决方案:

  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 方法里写上代码,最后代码如下:

  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!

后台全部代码如下:

  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;
  10. using System.Data.SqlClient;
  11. public partial class _Default : System.Web.UI.Page
  12. {
  13. SqlConnection sqlcon;
  14. SqlCommand sqlcom;
  15. string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";
  16. protected void Page_Load(object sender, EventArgs e)
  17. {
  18. if (!IsPostBack)
  19. {
  20. ViewState["SortOrder"] = "身份证号码";
  21. ViewState["OrderDire"] = "ASC";
  22. bind();
  23. }
  24. }
  25. protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
  26. {
  27. GridView1.EditIndex = e.NewEditIndex;
  28. bind();
  29. }
  30. protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  31. {
  32. string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
  33. sqlcon = new SqlConnection(strCon);
  34. sqlcom = new SqlCommand(sqlstr,sqlcon);
  35. sqlcon.Open();
  36. sqlcom.ExecuteNonQuery();
  37. sqlcon.Close();
  38. bind();
  39. }
  40. protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
  41. {
  42. sqlcon = new SqlConnection(strCon);
  43. string sqlstr = "update 飞狐工作室 set 姓名='"
  44. + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"
  45. + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"
  46. + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
  47. sqlcom=new SqlCommand(sqlstr,sqlcon);
  48. sqlcon.Open();
  49. sqlcom.ExecuteNonQuery();
  50. sqlcon.Close();
  51. GridView1.EditIndex = -1;
  52. bind();
  53. }
  54. protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  55. {
  56. GridView1.EditIndex = -1;
  57. bind();
  58. }
  59. public void bind()
  60. {
  61. string sqlstr = "select top 5 * from 飞狐工作室";
  62. sqlcon = new SqlConnection(strCon);
  63. SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
  64. DataSet myds = new DataSet();
  65. sqlcon.Open();
  66. myda.Fill(myds, "飞狐工作室");
  67. GridView1.DataSource = myds;
  68. GridView1.DataKeyNames = new string[] { "身份证号码" };
  69. GridView1.DataBind();
  70. sqlcon.Close();
  71. GridView1.Columns[3].Visible = false;
  72. CheckBox1.Checked = false;
  73. }
  74. protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
  75. {
  76. GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible;
  77. Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString());
  78. }
  79. }
复制代码
前台代码:

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

14.GridView弹出新页面:


  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!,很好用):


代码:

  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. position:relative ;
  9. table-layout:fixed;
  10. top:expression(this.offsetParent.scrollTop);
  11. z-index: 10;
  12. }
  13. .Freezing th{text-overflow:ellipsis;overflow:hidden;white-space: nowrap;padding:2px;}
  14. </style>
  15. </head>
  16. <body style="font-size=12px">
  17. <form id="form1" runat="server">
  18. <div style="overflow-y: scroll; height: 200px;width:300px" id="dvBody">
  19. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
  20. OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" OnRowCreated="GridView1_RowCreated" >
  21. <FooterStyle BackColor="White" ForeColor="#000066" />
  22. <Columns>
  23. <asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" />
  24. <asp:BoundField DataField="邮政编码" HeaderText="邮政编码" SortExpression="邮政编码" />
  25. <asp:BoundField DataField="家庭住址" HeaderText="家庭住址" />
  26. <asp:BoundField DataField="姓名" HeaderText="姓名" />
  27. </Columns>
  28. <RowStyle ForeColor="#000066" />
  29. <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
  30. <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/>
  31. <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" CssClass="Freezing"/>
  32. </asp:GridView>
  33. </div>
  34. </form>
  35. </body>
  36. </html>
复制代码

用法:CSS设如上的样式,HeaderStyle加CssClass="Freezing,套住GridView的Div设置高度宽度 

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


后台代码:

  

  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. }
复制代码
前台:

  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. </Columns>
  21. <RowStyle ForeColor="#000066" />
  22. <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
  23. <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/>
  24. <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
  25. </asp:GridView>
  26. </div>
  27. </form>
  28. </body>
  29. </html>
复制代码

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


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

  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();
复制代码

全部后台代码:

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


前台代码:

  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. </Columns>
  21. <RowStyle ForeColor="#000066" />
  22. <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
  23. <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/>
  24. <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
  25. </asp:GridView>
  26. </div>
  27. </form>
  28. </body>
  29. </html>
复制代码

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


解决方案

  1. private double sum = 0;//取指定列的数据和,你要根据具体情况对待可能你要处理的是int
  2. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  3. {
  4. if (e.Row.RowIndex >= 0)
  5. {
  6. sum += Convert.ToDouble(e.Row.Cells[6].Text);
  7. }
  8. else if (e.Row.RowType == DataControlRowType.Footer)
  9. {
  10. e.Row.Cells[5].Text = "总薪水为:";
  11. e.Row.Cells[6].Text = sum.ToString();
  12. e.Row.Cells[3].Text = "平均薪水为:";
  13. e.Row.Cells[4].Text = ((int)(sum / GridView1.Rows.Count)).ToString();
  14. }
  15. }
复制代码

后台全部代码:

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

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

  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. </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>
复制代码

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


解决方案:

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

  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. Response.Clear();
  14. Response.Buffer = true;
  15. Response.Charset = "GB2312";
  16. Response.AppendHeader("Content-Disposition", "attachment;filename=Message.xls");
  17. Response.ContentEncoding = System.Text.Encoding.UTF8;
  18. Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
  19. System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
  20. System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
  21. this.GridView1.RenderControl(oHtmlTextWriter);
  22. Response.Output.Write(oStringWriter.ToString());
  23. Response.Flush();
  24. Response.End();
  25. }
  26. public override void VerifyRenderingInServerForm(Control control)
  27. {
  28. //此段必须要,否则会报错,数据不能导入到EXCEL。
  29. }
复制代码


  1. [/code]
  2. //
  3. 如果没有下面方法会报错类型
  4. “GridView”
  5. 的控件
  6. “GridView1”
  7. 必须放在具有
  8.  runat=server 
  9. 的窗体标记内
  10. <p align="left" style="color:rgb(51,51,51)"></p>
  11. [code] public override void VerifyRenderingInServerForm(Control control)
  12. {
  13. }
复制代码

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

后台代码:

  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. public void bind()
  27. {
  28. string sqlstr = "select top 5 * from 飞狐工作室";
  29. sqlcon = new SqlConnection(strCon);
  30. SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
  31. DataSet myds = new DataSet();
  32. sqlcon.Open();
  33. myda.Fill(myds, "飞狐工作室");
  34. GridView1.DataSource = myds;
  35. GridView1.DataKeyNames = new string[] { "身份证号码" };
  36. GridView1.DataBind();
  37. sqlcon.Close();
  38. }
  39. protected void Button1_Click(object sender, EventArgs e)
  40. {
  41. Export("application/ms-excel", "学生成绩报表.xls");
  42. }
  43. private void Export(string FileType, string FileName)
  44. {
  45. Response.Charset = "GB2312";
  46. Response.ContentEncoding = System.Text.Encoding.UTF7;
  47. Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
  48. Response.ContentType = FileType;
  49. this.EnableViewState = false;
  50. StringWriter tw = new StringWriter();
  51. HtmlTextWriter hw = new HtmlTextWriter(tw);
  52. GridView1.RenderControl(hw);
  53. Response.Write(tw.ToString());
  54. Response.End();
  55. }
  56. public override void VerifyRenderingInServerForm(Control control)
  57. {
  58. }
  59. }
复制代码
前台:

  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. </Columns>
  12. <RowStyle ForeColor="#000066" />
  13. <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
  14. <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/>
  15. <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
  16. </asp:GridView>
  17. <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出" />
复制代码
读取 Excel 数据的代码:这个很简单的

  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/zdhlwt2008/article/details/51395684
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?会员注册

×
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-26 12:04 , Processed in 0.444979 second(s), 27 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表