GridView学习笔记

GridView是ASP.NET提供的四大数据控件之一,拥有选择、排序、分页和编辑等强大功能。本文作一简单介绍,欢迎大家拍砖和指正。

1.基本数据访问方法,主要是增删改查等,为后续做好准备,数据访问使用已封装的类(本文不讨论该封装类)。

代码
 1     public class GetData
 2     {
 3         private static string conStr = "Test";
 4 
 5         public static void InsertStudent(string name, bool sex, string courseID, int score, DateTime operTime)
 6         {
 7             Database db = new Database(conStr);
 8             string sql = @"INSERT INTO student (NAME,SEX,COURSE,SCORE,OPER_TIME) 
 9             VALUES (@name,@sex,@courseID,@score,@operTime)";
10             DbCommand command = db.GetSqlStringCommand(sql);
11             db.AddInParameter(command, "@name", DbType.AnsiString, name);
12             db.AddInParameter(command, "@sex", DbType.Boolean, sex);
13             db.AddInParameter(command, "@courseID", DbType.AnsiString, courseID);
14             db.AddInParameter(command, "@score", DbType.Int32, score);
15             db.AddInParameter(command, "@operTime", DbType.DateTime, operTime);
16             db.ExecuteNonQuery(command);
17         }
18 
19         public static void DeleteStudent(string id)
20         {
21             Database db = new Database(conStr);
22             string sql = "DELETE FROM student WHERE ID=@id";
23             DbCommand command = db.GetSqlStringCommand(sql);
24             db.AddInParameter(command, "@id", DbType.AnsiString, id);
25             db.ExecuteNonQuery(command);
26         }
27 
28         public static void UpdateStudent(string id, string name, bool sex, string courseID, int score, DateTime operTime)
29         {
30             Database db = new Database(conStr);
31             string sql = @"UPDATE student SET NAME=@name,SEX=@sex,COURSE=@courseID,SCORE=@score,
32             OPER_TIME=@operTime WHERE ID=@id";
33             DbCommand command = db.GetSqlStringCommand(sql);
34             db.AddInParameter(command, "@id", DbType.AnsiString, id);
35             db.AddInParameter(command, "@name", DbType.AnsiString, name);
36             db.AddInParameter(command, "@sex", DbType.Boolean, sex);
37             db.AddInParameter(command, "@courseID", DbType.AnsiString, courseID);
38             db.AddInParameter(command, "@score", DbType.Int32, score);
39             db.AddInParameter(command, "@operTime", DbType.DateTime, operTime);
40             db.ExecuteNonQuery(command);
41         }
42 
43         public static DataTable GetStudentList()
44         {
45             Database db = new Database(conStr);
46             string sql = "select * from student";
47             DbCommand command = db.GetSqlStringCommand(sql);
48             return db.ExecuteDataTable(command);
49         }
50 
51         public static DataTable GetCourseList()
52         {
53             Database db = new Database(conStr);
54             string sql = "select * from course";
55             DbCommand command = db.GetSqlStringCommand(sql);
56             return db.ExecuteDataTable(command);
57         }
58     }

2.使用标准列进行修改和删除

 2.1  前台

代码
 1 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
 2     AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" OnRowCancelingEdit="GridView1_RowCancelingEdit"
 3     OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
 4     OnRowDataBound="GridView1_RowDataBound">
 5     <Columns>
 6         <asp:BoundField DataField="NAME" HeaderText="姓名" />
 7         <asp:BoundField DataField="SEX" HeaderText="性别" />
 8         <asp:BoundField DataField="COURSE" HeaderText="课程" />
 9         <asp:BoundField DataField="SCORE" HeaderText="成绩" />
10         <asp:BoundField DataField="OPER_TIME" HeaderText="时间" DataFormatString="{0:yyyy年MM月dd日 HH时mm分ss秒}" />
11     </Columns>
12 </asp:GridView>

 常用格式化公式:货币{0:C},科学计数法{0:E},百分比{0:P},固定浮点数{0:F?}(?表示小数位数),日期{0:yyyy-MM-dd HH:mm:ss}。

 2.2  修改

代码
 1 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
 2 {
 3     GridView1.EditIndex = e.NewEditIndex;
 4     BindSource();
 5 }
 6 
 7 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
 8 {
 9     string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
10     string name =  e.NewValues["NAME"].ToString();
11     bool sex = Convert.ToBoolean(e.NewValues["SEX"].ToString());
12     string course = e.NewValues["COURSE"].ToString();
13     int score = Convert.ToInt32(e.NewValues["SCORE"].ToString());
14     DateTime operTime = Convert.ToDateTime(e.NewValues["OPER_TIME"].ToString());
15     GetData.UpdateStudent(id, name, sex, course, score, operTime);
16     GridView1.EditIndex = -1;
17     BindSource();
18 }
19 
20 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
21 {
22     GridView1.EditIndex = -1;
23     BindSource();
24 }

 2.3  删除

代码
1 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
2 {
3     string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
4     GetData.DeleteStudent(id);
5     BindSource();
6 }

 2.4  格式化特定值

代码
1 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
2 {
3     if (e.Row.RowType == DataControlRowType.DataRow)
4     {
5         e.Row.Cells[2].Text = Convert.ToBoolean(e.Row.Cells[2].Text.Trim()) == false ? "" : "";
6     }
7 }

备注:性别列将true或者false转换成男或者女进行显示。

 2.5  绑定数据源

代码
1 private void BindSource()
2 {
3     GridView1.DataSource = GetData.GetStudentList();
4     GridView1.DataBind();
5 }

3.使用模板列进行修改和删除

 3.1  前台

代码
 1 <asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" AutoGenerateColumns="False"
 2     OnRowEditing="GridView1_OnEditCommand" OnRowUpdating="GridView1_OnUpdateCommand"
 3     OnRowCancelingEdit="GridView1_OnCancelCommand" OnRowDeleting="GridView1_OnDeleteCommand">
 4     <Columns>
 5         <asp:TemplateField HeaderText="姓名">
 6             <ItemTemplate>
 7                 <%# Eval("NAME")%>
 8             </ItemTemplate>
 9             <EditItemTemplate>
10                 <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("NAME")%>'></asp:TextBox>
11             </EditItemTemplate>
12         </asp:TemplateField>
13         <asp:TemplateField HeaderText="性别">
14             <ItemTemplate>
15                 <%# Eval("SEX")%>
16             </ItemTemplate>
17             <EditItemTemplate>
18                 <asp:TextBox ID="txtSex" runat="server" Text='<%# Bind("SEX")%>'></asp:TextBox>
19             </EditItemTemplate>
20         </asp:TemplateField>
21         <asp:TemplateField HeaderText="课程">
22             <ItemTemplate>
23                 <%# Eval("COURSE")%>
24             </ItemTemplate>
25             <EditItemTemplate>
26                 <asp:TextBox ID="txtCourse" runat="server" Text='<%# Bind("COURSE")%>'></asp:TextBox>
27             </EditItemTemplate>
28         </asp:TemplateField>
29         <asp:TemplateField HeaderText="成绩">
30             <ItemTemplate>
31                 <%# Eval("SCORE")%>
32             </ItemTemplate>
33             <EditItemTemplate>
34                 <asp:TextBox ID="txtScore" runat="server" Text='<%# Bind("SCORE")%>'></asp:TextBox>
35             </EditItemTemplate>
36         </asp:TemplateField>
37         <asp:TemplateField HeaderText="时间">
38             <ItemTemplate>
39                 <%# Eval("OPER_TIME","{0:yyyy年MM月dd日 HH时mm分ss秒}")%>
40             </ItemTemplate>
41             <EditItemTemplate>
42                 <asp:TextBox ID="txtOperTime" runat="server" Text='<%# Bind("OPER_TIME")%>'></asp:TextBox>
43             </EditItemTemplate>
44         </asp:TemplateField>
45         <asp:TemplateField HeaderText="操作">
46             <ItemTemplate>
47                 <asp:Button ID="Button1" runat="server" Text="编辑" CommandName="edit" />
48                 <asp:Button ID="Button2" runat="server" Text="删除" CommandName="delete" />
49             </ItemTemplate>
50             <EditItemTemplate>
51                 <asp:Button ID="Button1" runat="server" Text="更新" CommandName="Update" />
52                 <asp:Button ID="Button2" runat="server" Text="取消" CommandName="Cancel" />
53             </EditItemTemplate>
54         </asp:TemplateField>
55     </Columns>
56 </asp:GridView>

 备注:绑定一个编辑值到控件时,必须在数据绑定表达式中使用Bind()方法而不是通常的Eval()方法。只有Bind()方法才会创建双向链接,更新后的值才能送回到服务器。谨记:提交更新时,只提交被绑定的、可编辑的参数。

 3.2  修改

代码
 1 protected void GridView1_OnEditCommand(object sender, GridViewEditEventArgs e)
 2 {
 3     GridView1.EditIndex = e.NewEditIndex;
 4     BindSource();
 5 }
 6 
 7 protected void GridView1_OnUpdateCommand(object sender, GridViewUpdateEventArgs e)
 8 {
 9     string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
10     GridViewRow gv = GridView1.Rows[e.RowIndex];
11     string name = ((TextBox)gv.FindControl("txtName")).Text.Trim();
12     bool sex = Convert.ToBoolean(((TextBox)gv.FindControl("txtSex")).Text.Trim());
13     string course = ((TextBox)gv.FindControl("txtCourse")).Text.Trim();
14     int score = Convert.ToInt32(((TextBox)gv.FindControl("txtScore")).Text.Trim());
15     DateTime operTime = Convert.ToDateTime(((TextBox)gv.FindControl("txtOperTime")).Text.Trim());
16     GetData.UpdateStudent(id, name, sex, course, score, operTime);
17     GridView1.EditIndex = -1;
18     BindSource();
19 }
20 
21 protected void GridView1_OnCancelCommand(object sender, GridViewCancelEditEventArgs e)
22 {
23     GridView1.EditIndex = -1;
24     BindSource();
25 }

 3.3  删除

代码
1 protected void GridView1_OnDeleteCommand(object sender, GridViewDeleteEventArgs e)
2 {
3     string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
4     GetData.DeleteStudent(id);
5     BindSource();
6 }

 

posted @ 2013-05-04 09:34  九极天  阅读(228)  评论(0编辑  收藏  举报