Fork me on GitHub
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridviewPage.aspx.cs" Inherits="GridviewPage" %>

<!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 Page</title>
    <link href="~/CSS/Gridview.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div id="container">
        <asp:GridView ID="GridView1" ShowFooter="false" BorderColor="Black" OnRowDataBound="GridView1_RowDataBound"  runat="server" AutoGenerateColumns="False"  Font-Size="12px" Width="549px"  AllowPaging="True" >
          <Columns>
            <asp:BoundField DataField="ID" HeaderText="编号" />
            <asp:BoundField DataField="EmpID" HeaderText="账号" />
            <asp:BoundField DataField="EmpRealName" HeaderText="姓名" />
            <asp:BoundField DataField="EmpSex" HeaderText="性别" />
            <asp:BoundField DataField="EmpAddress" HeaderText="住址" />
            <asp:BoundField DataField="EmpZipCode" HeaderText="邮编" />
            <asp:BoundField DataField="EmpBirthday" HeaderText="生日" DataFormatString="{0:yyyy-MM-dd}" HtmlEncode="False" />
            <asp:BoundField DataField="EmpSalary" HeaderText="薪水" DataFormatString="{0:c}" HtmlEncode="False" />
          </Columns>
          <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" />
          <RowStyle HorizontalAlign="Center" />
          <PagerStyle HorizontalAlign="Center" BackColor="#FFFFCC" BorderStyle="None" BorderWidth="0px" ForeColor="#330099" />
            <PagerSettings Visible="False" />
        </asp:GridView>
        <br />
        <asp:LinkButton ID="lnkbtnFrist" runat="server" OnClick="lnkbtnFrist_Click">首页</asp:LinkButton> 
        <asp:LinkButton ID="lnkbtnPre" runat="server" OnClick="lnkbtnPre_Click">上一页</asp:LinkButton> 
        <asp:Label ID="lblCurrentPage" runat="server"></asp:Label> 
        <asp:LinkButton ID="lnkbtnNext" runat="server" OnClick="lnkbtnNext_Click">下一页</asp:LinkButton> 
        <asp:LinkButton ID="lnkbtnLast" runat="server" OnClick="lnkbtnLast_Click">尾页</asp:LinkButton> 
跳转到第<asp:DropDownList ID="ddlCurrentPage" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> 
        </asp:DropDownList></div>
    </form>
</body>
</html>
 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 /// <summary>
12 /// Author:匆匆  Blog:http://www.cnblogs.com/huangjianhuakarl/
13 /// Gridview自定义分页页码
14 /// </summary>
15 public partial class GridviewPage : System.Web.UI.Page
16 {
17     protected void Page_Load(object sender, EventArgs e)
18     {
19         if (!IsPostBack)
20         {
21             bind();
22         }
23     }
24     /// <summary>
25     /// 绑定数据
26     /// </summary>
27     public void bind()
28     {
29         string sqlStr = "select * from Employee";
30         DataSet myds = Common.dataSet(sqlStr);
31         GridView1.DataSource = myds;
32         GridView1.DataKeyNames = new string[] { "ID" };
33         GridView1.DataBind();
34         this.ddlCurrentPage.Items.Clear();
35         for (int i = 1; i <= this.GridView1.PageCount; i++)
36         {
37             this.ddlCurrentPage.Items.Add(i.ToString());
38         }
39         this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
40     }
41     /// <summary>
42     /// 在 GridView 控件中的某个行被绑定到一个数据记录时发生。此事件通常用于在某个行被绑定到数据时修改该行的内容。
43     /// </summary>
44     /// <param name="sender"></param>
45     /// <param name="e"></param>
46     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
47     {
48         this.lblCurrentPage.Text = string.Format("当前第{0}页/总共{1}页", this.GridView1.PageIndex + 1, this.GridView1.PageCount); 
49 
50         //遍历所有行设置边框样式
51         foreach (TableCell tc in e.Row.Cells)
52         {
53             tc.Attributes["style"] = "border-color:Black";
54         }
55         //用索引来取得编号
56         if (e.Row.RowIndex != -1)
57         {
58             int id = GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1;
59             e.Row.Cells[0].Text = id.ToString();
60         }
61         
62     }
63     /// <summary>
64     /// 重新绑定
65     /// </summary>
66     /// <param name="sender"></param>
67     /// <param name="e"></param>
68     protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
69     {
70         this.GridView1.PageIndex = this.ddlCurrentPage.SelectedIndex;
71         bind();
72     }
73     protected void lnkbtnFrist_Click(object sender, EventArgs e)
74     {
75         this.GridView1.PageIndex = 0;
76         bind();
77     }
78     protected void lnkbtnPre_Click(object sender, EventArgs e)
79     {
80         if (this.GridView1.PageIndex > 0)
81         {
82             this.GridView1.PageIndex = this.GridView1.PageIndex - 1;
83             bind();
84         }
85     }
86     protected void lnkbtnNext_Click(object sender, EventArgs e)
87     {
88         if (this.GridView1.PageIndex < this.GridView1.PageCount)
89         {
90             this.GridView1.PageIndex = this.GridView1.PageIndex + 1;
91             bind();
92         }
93     }
94     protected void lnkbtnLast_Click(object sender, EventArgs e)
95     {
96         this.GridView1.PageIndex = this.GridView1.PageCount;
97         bind();
98     } 
99 }

 

 91 单元格中触发的事件,并且两个窗体之间的传值
 92 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
 93         {
 94             string name=dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
 95             string psw=dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value.ToString();
 96             Form1 form1 = new Form1();//这里是两个窗体之间传递值,需要设置两个字段
 97             form1.name = name;
 98             form1.psw = psw;
 99             form1.Show(); 
100         }
101 获得当前单元格的内容也就是当前行第一列的值
102 Console.WriteLine(DataGridView1.CurrentCell.Value);
103 // 取得当前单元格的列 Index
104 Console.WriteLine(DataGridView1.CurrentCell.ColumnIndex);
105 // 取得当前单元格的行 Index
106 Console.WriteLine(DataGridView1.CurrentCell.RowIndex);
107 ' 删除名为"Column1"的列
108 DataGridView1.Columns.Remove("Column1");
109 ' 删除第一列
110 DataGridView1.Columns.RemoveAt(0);
111 移除当前行
112 this.dataGridView1.Rows.Remove(this.dataGridView1.CurrentRow);
113 ' 删除第一行
114 DataGridView1.Rows.RemoveAt(0);
115 获得此格的内容
116 DataGridView1【0,0】;
117 dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.MistyRose;//偶数行显示
118 dataGridView1.RowsDefaultCellStyle.BackColor = Color.MistyRose;//奇数行显示
119 显示选择的行
120 
128 DataGridView的异常处理
129 1、    CellFormatting事件,每绘制一个单元格系统自动触发此事件
130 private void buttonCellValidating_Click(object sender, EventArgs e)
131         {
132             dataGridView1.CellValidating +=
133                 new DataGridViewCellValidatingEventHandler(CellValidating);
134             MessageBox.Show("");
135 
136         }
137         private void CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
138         {
139             string errorMessage = "";
140             if (dataGridView1.Columns[e.ColumnIndex].Name == "学号")
141             {
142                 if (e.FormattedValue == null)
143                 {
144                     errorMessage = "不允许空值";
145                 }
146                 else
147                 {
148                     string xuehao = e.FormattedValue.ToString();
149                     if (xuehao.Length != 8)
150                     {
151                         errorMessage = "学号必须为8位数字";
152                     }
153                     else
154                     {
155                         for (int i = 0; i < xuehao.Length; i++)
156                         {
157                             if (char.IsDigit(xuehao[i]) == false)
158                             {
159                                 errorMessage = "学号必须为8位数字";
160                                 break;
161                             }
162                         }
163                     }
164                 }
165             }
166 2、DataError事件,如果用户输入了不符合数据源规定的内容,系统在验证数据时就会产生异常
167 3、CellVaildating事件,当用户提交数据时响应这些事件
168 
169 
170 
171 
172 if (errorMessage.Length > 0)
173             {
174                 MessageBox.Show(errorMessage, string.Format("第{0}行第{1}列有错",
175                      e.RowIndex, e.ColumnIndex));
176                 dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = errorMessage;//如果用户输入的值无效就可以触发这些事件
177             }
178             else
179             {
180                 dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = null;
181             }

 

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo h = dataGridView1.HitTest(e.X, e.Y);
            if (h.Type== DataGridViewHitTestType.Cell || h.Type == DataGridViewHitTestType.RowHeader)
            {
                dataGridView1.Rows[h.RowIndex].Selected = true;
                //鼠标点时可以获得一行数据,不管点任何一行都是一行数据
                int processeId = (int)dataGridView1.CurrentRow.Cells[0].Value;
                ShowProcessInfo(Process.GetProcessById(processeId));
            }
        }

 

 

posted on 2013-10-08 22:27  lingfeng95  阅读(368)  评论(0编辑  收藏  举报