c# gridview控件中添、删、改、查数据
主要是实现类似于jQGrid那种页面效果
大佬整理的,借鉴一下
1)前台代码如下
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridViewDemo._Default" %> <!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></title> <style type="text/css"> body{ font-size:12px;} </style> <script language="javascript" type="text/javascript"> function deleteStudent() { if(!confirm('are you sure to delete this student?')) { return false; } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="gvwStudent" runat="server" AutoGenerateColumns="False" ShowFooter="true" onrowcommand="gvwStudent_RowCommand"> <Columns> <%--编号--%> <asp:TemplateField HeaderText="id"> <ItemTemplate> <%#Eval("studentID") %> </ItemTemplate> <EditItemTemplate> <%#Eval("studentID") %> </EditItemTemplate> </asp:TemplateField> <%--姓名--%> <asp:TemplateField HeaderText="name"> <ItemTemplate> <%#Eval("studentName") %> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtStudentName" runat="server" Text='<%#Eval("studentName") %>'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtStudentName" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <%--性别--%> <asp:TemplateField HeaderText="sex"> <ItemTemplate> <%#Eval("studentSex") %> </ItemTemplate> <EditItemTemplate> <asp:RadioButton ID="rbtnMale" Text="male" runat="server" GroupName="1" Checked='<%#Eval("studentSex").ToString()=="male"?true:false %>'/> <asp:RadioButton ID="rbtnFemale" Text="female" runat="server" GroupName="1" Checked='<%#Eval("studentSex").ToString()=="female"?true:false %>' /> </EditItemTemplate> <FooterTemplate> <asp:RadioButton ID="rbtnMale" Text="male" runat="server" GroupName="1" Checked="true"/> <asp:RadioButton ID="rbtnFemale" Text="female" runat="server" GroupName="1" /> </FooterTemplate> </asp:TemplateField> <%--年龄--%> <asp:TemplateField HeaderText="age"> <ItemTemplate> <%#Eval("studentAge") %> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtAge" runat="server" Text='<%#Eval("studentAge") %>'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtAge" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <%--修改--%> <asp:TemplateField HeaderText="edit"> <ItemTemplate> <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="studentEdit" CommandArgument='<%#Eval("studentID") %>'>Edit</asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="lbtnUpdate" runat="server" CommandName="studentUpdate" CommandArgument='<%#Eval("studentID") %>'>Update</asp:LinkButton> </EditItemTemplate> <FooterTemplate> <asp:LinkButton ID="lbtnSave" runat="server" CommandName="studentAdd">Add</asp:LinkButton> </FooterTemplate> </asp:TemplateField> <%--删除--%> <asp:TemplateField HeaderText="delete"> <ItemTemplate> <asp:LinkButton ID="lbtnDelete" runat="server" CommandName="studentDelete" CommandArgument='<%#Eval("studentID") %>' OnClientClick="return deleteStudent();">Delete</asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Label ID="lblMessage" runat="server" Text="" style=" color:Red;"></asp:Label> </div> </form> </body> </html>
2)后台代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.Linq; using System.Data; namespace WebApplication7 { public partial class _Default : System.Web.UI.Page { string nodata = "no data!"; StudentClassesDataContext scdc = new StudentClassesDataContext(@"server=.\sqlexpress;database=School;uid=sa;pwd=1"); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindStudent(); } else//防止PostBack时页面显示变化 { if (gvwStudent.Rows.Count == 1 && gvwStudent.Rows[0].Cells[0].Text == nodata) { int columnCount = gvwStudent.Columns.Count; gvwStudent.Rows[0].Cells.Clear(); gvwStudent.Rows[0].Cells.Add(new TableCell()); gvwStudent.Rows[0].Cells[0].ColumnSpan = columnCount; gvwStudent.Rows[0].Cells[0].Text = nodata; gvwStudent.Rows[0].Cells[0].Style.Add("text-align", "center"); } } } /// <summary> /// bind student /// </summary> private void BindStudent() { Table<Student> students = scdc.GetTable<Student>(); //gvwStudent.DataSource = from student in students where student.studentSex == "male" select student; if (students.Count() > 0) { gvwStudent.DataSource = students; gvwStudent.DataBind(); } else//增加空行来显示GridView的结构 { DataTable dtStudent = new DataTable(); dtStudent.Columns.Add(new DataColumn("studentID")); dtStudent.Columns.Add(new DataColumn("studentName")); dtStudent.Columns.Add(new DataColumn("studentSex")); dtStudent.Columns.Add(new DataColumn("studentAge")); if (dtStudent.Rows.Count == 0) { dtStudent.Rows.Add(dtStudent.NewRow()); } gvwStudent.DataSource = dtStudent; gvwStudent.DataBind(); int columnCount = gvwStudent.Columns.Count; gvwStudent.Rows[0].Cells.Clear(); gvwStudent.Rows[0].Cells.Add(new TableCell()); gvwStudent.Rows[0].Cells[0].ColumnSpan = columnCount; gvwStudent.Rows[0].Cells[0].Text = nodata; gvwStudent.Rows[0].Cells[0].Style.Add("text-align", "center"); } } protected void gvwStudent_RowCommand(object sender, GridViewCommandEventArgs e) { switch (e.CommandName) { case "studentAdd"://添加 { //获取选中行 GridViewRow gridViewRow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer; //姓名 TextBox txtStudentName = (TextBox)gridViewRow.FindControl("txtStudentName"); string studentName = txtStudentName.Text.Trim(); if (studentName == "") { lblMessage.Text = "please input student name!"; return; } //性别 RadioButton rbtnMale = (RadioButton)gridViewRow.FindControl("rbtnMale"); string studentSex = rbtnMale.Checked ? rbtnMale.Text : ((RadioButton)gridViewRow.FindControl("rbtnFemale")).Text; //年龄 TextBox txtAge = (TextBox)gridViewRow.FindControl("txtAge"); string age = txtAge.Text.Trim(); int studentAge = 0; if (!Int32.TryParse(age, out studentAge)) { lblMessage.Text = "please input currect student age!"; return; } Student item = new Student(); item.studentName = studentName; item.studentSex = studentSex; item.studentAge = studentAge; if (AddStudent(item)) { lblMessage.Text = "add student success!"; BindStudent(); } else { lblMessage.Text = "add student failure!"; } } break; case "studentDelete"://删除 { int studentID = 0; if (!Int32.TryParse(e.CommandArgument.ToString(), out studentID)) { lblMessage.Text = "student's id is error"; } if (DeleteStudent(studentID)) { lblMessage.Text = "delete student success!"; BindStudent(); } else { lblMessage.Text = "delete student failure!"; } } break; case "studentEdit"://修改 { GridViewRow gridViewRow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer; int index = gridViewRow.RowIndex; gvwStudent.EditIndex = index; BindStudent(); break; } case "studentUpdate"://更新 { int studentID = 0; if (!Int32.TryParse(e.CommandArgument.ToString(), out studentID)) { lblMessage.Text = "student's id is error"; } Student item = GetStudent(studentID); //获取选中行 GridViewRow gridViewRow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer; //姓名 TextBox txtStudentName = (TextBox)gridViewRow.FindControl("txtStudentName"); string studentName = txtStudentName.Text.Trim(); if (studentName == "") { lblMessage.Text = "please input student name!"; return; } //性别 RadioButton rbtnMale = (RadioButton)gridViewRow.FindControl("rbtnMale"); string studentSex = rbtnMale.Checked ? rbtnMale.Text : ((RadioButton)gridViewRow.FindControl("rbtnFemale")).Text; //年龄 TextBox txtAge = (TextBox)gridViewRow.FindControl("txtAge"); string age = txtAge.Text.Trim(); int studentAge = 0; if (!Int32.TryParse(age, out studentAge)) { lblMessage.Text = "please input currect student age!"; return; } item.studentName = studentName; item.studentSex = studentSex; item.studentAge = studentAge; if (UpdateStudent(item)) { lblMessage.Text = "update student success!"; gvwStudent.EditIndex = -1; BindStudent(); } else { lblMessage.Text = "update student failure!"; } } break; default: break; } } /// <summary> /// 更新 /// </summary> /// <param name="item"></param> /// <returns></returns> private bool UpdateStudent(Student item) { bool flag = false; try { scdc.SubmitChanges(); flag = true; } catch (Exception ex) { flag = false; } return flag; } /// <summary> /// 获取学生 /// </summary> /// <param name="studentID"></param> /// <returns></returns> private Student GetStudent(int studentID) { Student item = new Student(); item = scdc.Student.SingleOrDefault(s => s.studentID == studentID); return item; } /// <summary> /// 删除 /// </summary> /// <param name="studentID"></param> /// <returns></returns> private bool DeleteStudent(int studentID) { bool flag = false; try { Student item = scdc.Student.SingleOrDefault(s => s.studentID == studentID); scdc.Student.DeleteOnSubmit(item); scdc.SubmitChanges(); flag = true; } catch (Exception ex) { flag = false; } return flag; } /// <summary> /// 添加 /// </summary> /// <param name="item"></param> /// <returns></returns> private bool AddStudent(Student item) { bool flag = false; try { scdc.Student.InsertOnSubmit(item); scdc.SubmitChanges(); flag = true; } catch (Exception ex) { flag = false; } return flag; } } }