9.GridView实现自动编号
效果图:


实现方法:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:
 1protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 2{
 3    //如果是绑定数据行 //清清月儿http://blog.csdn.net/21aspnet
 4    if (e.Row.RowType == DataControlRowType.DataRow)
 5    {
 6        ////鼠标经过时,行背景色变
 7        //e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");
 8        ////鼠标移出时,行背景色变
 9        //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
10        ////当有编辑列时,避免出错,要加的RowState判断
11        //if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
12        //{
13        //    ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:"" + e.Row.Cells[1].Text + ""吗?')");
14        //}
15    }

16    if (e.Row.RowIndex != -1)
17    {
18        int id = e.Row.RowIndex + 1;
19        e.Row.Cells[0].Text = id.ToString();
20    }

21}
 
注意这时最好把前台的第一列的表头该为“编号”,因为以前的第一列被“吃掉”了。
 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实现自定义时间货币等字符串格式:
效果图:

图1-未格式化前
 
图2-格式化后
 
解决方法:
在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:GridView>
将htmlencode设置为false即可
 
另外的解决方法为,使用模版列
 1<asp:GridView ID="GridView3" runat="server" >
 2 <columns>
 3  <asp:TemplateField HeaderText="CreationDate" >
 4   <itemtemplate>
 5    <asp:Label ID="Label1" runat="server" Text='<%# Bind("CreationDate", "{0:M-dd-yyyy}") %>' />
 6   </itemtemplate>
 7   <edititemtemplate>
 8    <asp:Label ID="Label1" runat="server" Text='<%# Eval("CreationDate", "{0:M-dd-yyyy}") %>' />
 9   </edititemtemplate>
10  </asp:TemplateField>
11 </columns>
12</asp:GridView>
 
前台代码:
 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实现用“...”代替超长字符串:
效果图:
解决方法:数据绑定后过滤每一行即可
 1for (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}
 
调用的方法:
 1public 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}
 
后台全部代码:
  1using System;
  2using System.Data;
  3using System.Configuration;
  4using System.Web;
  5using System.Web.Security;
  6using System.Web.UI;
  7using System.Web.UI.WebControls;
  8using System.Web.UI.WebControls.WebParts;
  9using System.Web.UI.HtmlControls;
 10using System.Data.SqlClient;
 11public partial class _Default : System.Web.UI.Page
 12{
 13    SqlConnection sqlcon;
 14    SqlCommand sqlcom;
 15    string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";
 16    protected void Page_Load(object sender, EventArgs e)
 17    {
 18        if (!IsPostBack)
 19        {
 20            ViewState["SortOrder"] = "身份证号码";
 21            ViewState["OrderDire"] = "ASC";
 22            bind();
 23        }

 24    }

 25    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
 26    {
 27        GridView1.EditIndex = e.NewEditIndex;
 28        bind();
 29    }

 30    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
 31    {
 32        string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
 33        sqlcon = new SqlConnection(strCon);
 34        sqlcom = new SqlCommand(sqlstr,sqlcon);
 35        sqlcon.Open();
 36        sqlcom.ExecuteNonQuery();
 37        sqlcon.Close();
 38        bind();
 39    }

 40    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
 41    {
 42        sqlcon = new SqlConnection(strCon);
 43        string sqlstr = "update 飞狐工作室 set 姓名='"
 44            + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"
 45            + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='" 
 46            + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
 47        sqlcom=new SqlCommand(sqlstr,sqlcon);
 48        sqlcon.Open();
 49        sqlcom.ExecuteNonQuery();
 50        sqlcon.Close();
 51        GridView1.EditIndex = -1;
 52        bind();
 53    }

 54    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
 55    {
 56        GridView1.EditIndex = -1;
 57        bind();
 58    }

 59    public void bind()
 60    {
 61        string sqlstr = "select top 5 * from 飞狐工作室";
 62        sqlcon = new SqlConnection(strCon);
 63        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
 64        DataSet myds = new DataSet();
 65        sqlcon.Open();
 66        myda.Fill(myds, "飞狐工作室");
 67        GridView1.DataSource = myds;
 68        GridView1.DataKeyNames = new string[] { "身份证号码" };
 69        GridView1.DataBind();
 70        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
 71        {
 72            DataRowView mydrv;
 73            string gIntro;
 74            if (GridView1.PageIndex == 0)
 75            {
 76                mydrv = myds.Tables["飞狐工作室"].DefaultView[i];
 77                gIntro = Convert.ToString(mydrv["家庭住址"]);
 78                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);
 79            }

 80            else
 81            {
 82                mydrv = myds.Tables["飞狐工作室"].DefaultView[i + (5 * GridView1.PageIndex)];
 83                gIntro = Convert.ToString(mydrv["家庭住址"]);
 84                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);
 85            }

 86        }

 87        
 88        sqlcon.Close();
 89    }

 90    public string SubStr(string sString, int nLeng)
 91    {
 92        if (sString.Length <= nLeng)
 93        {
 94            return sString;
 95        }

 96        string sNewStr = sString.Substring(0, nLeng);
 97        sNewStr = sNewStr + "";
 98        return sNewStr;
 99    }

100    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
101    {
102        //如果是绑定数据行
103        if (e.Row.RowType == DataControlRowType.DataRow)
104        {
105            ////鼠标经过时,行背景色变
106            //e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");
107            ////鼠标移出时,行背景色变
108            //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
109            ////当有编辑列时,避免出错,要加的RowState判断
110            //if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
111            //{
112            //    ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:"" + e.Row.Cells[1].Text + ""吗?')");
113            //}
114        }

115        if (e.Row.RowIndex != -1)
116        {
117            int id = e.Row.RowIndex + 1;
118            e.Row.Cells[0].Text = id.ToString();
119        }

120    }

121}

 12.GridView一般换行与强制换行:
效果图:
 
首先设置<asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  ItemStyle-Width="100" />
gridview里有一列绑定的数据很长,显示的时候在一行里面显示,页面拉得很宽。
原因是连续英文段为一个整体导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add("word-break", "break-all")就可以。
如果要给所有的列增加此属性:
 1protected 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显示隐藏某一列:
本方案为月儿独创,不同于网上其他方式,我觉得用一个CheckBox更人性化,这样可以隐藏不必要的列,让用户自己选择需要出现的列,在处理多列时这是一个很好的解决方案!
效果图:

图1-开始
 
图2-点击显示的CheckBox后

解决方案:
 1public 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方法里写上代码,最后代码如下:
1protected 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!
后台全部代码如下:
 1using System;
 2using System.Data;
 3using System.Configuration;
 4using System.Web;
 5using System.Web.Security;
 6using System.Web.UI;
 7using System.Web.UI.WebControls;
 8using System.Web.UI.WebControls.WebParts;
 9using System.Web.UI.HtmlControls;
10using System.Data.SqlClient;
11public 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>