你的位置:首页 > ASP.net教程

[ASP.net教程]GridView数据绑定


 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebApplication1.Index"%> 2  3 <!DOCTYPE html> 4  5 <html "http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8   <title></title> 9 </head>10 <body>11   <form id="form1" runat="server">12   <div>13     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">14       <Columns>15         <asp:TemplateField HeaderText="全选" >16           <HeaderTemplate>17             <asp:CheckBox ID="CheckBox1" runat="server" Text="全选" onclick="checkAll(this)" />18           </HeaderTemplate>19           <ItemTemplate>20             <asp:CheckBox ID="CheckBox2" runat="server" />21             <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("stuID") %>' />22           </ItemTemplate>23         </asp:TemplateField>24         <asp:BoundField DataField="stuName" HeaderText="姓名" />25         <asp:BoundField DataField="stuNo" HeaderText="学号" />26         <asp:BoundField DataField="sex" HeaderText="性别" />27         <asp:TemplateField HeaderText="操作">28           <ItemTemplate>29             <asp:Button ID="Button2" runat="server" Text="编辑" CommandArgument='<%# Eval("stuID") %>' OnClick="Button2_Click" />30             <asp:Button ID="Button3" runat="server" Text="删除" CommandArgument='<%# Eval("stuID") %>' OnClick="Button3_Click" />31           </ItemTemplate>32         </asp:TemplateField>33       </Columns>34       <FooterStyle BackColor="White" ForeColor="#000066" />35       <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />36       <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />37       <PagerTemplate>38         <asp:Button ID="Button1" runat="server" Text="Button" />39       </PagerTemplate>40       <RowStyle ForeColor="#000066" />41       <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />42       <SortedAscendingCellStyle BackColor="#F1F1F1" />43       <SortedAscendingHeaderStyle BackColor="#007DBB" />44       <SortedDescendingCellStyle BackColor="#CAC9C9" />45       <SortedDescendingHeaderStyle BackColor="#00547E" />46     </asp:GridView> 47     <asp:Button ID="Button4" runat="server" Text="新增" OnClick="Button4_Click" />48   </div>49   </form>50 </body>51 </html>52 <script type="text/javascript">53   function checkAll(v){54     var arr = document.getElementById("GridView1").getElementsByTagName("input");55     for (var i = 0; i < arr.length; i++) {56       if (arr[i].type == "checkbox")57       {58         arr[i].checked = v.checked;59       }60     }61 62   }63 </script>

Index页面
 1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Data.SqlClient; 5 using System.Linq; 6 using System.Text; 7 using System.Web; 8 using System.Web.UI; 9 using System.Web.UI.WebControls;10 11 namespace WebApplication112 {13   public partial class Index : System.Web.UI.Page14   {15     protected void Page_Load(object sender, EventArgs e)16     {17       BindeList();18     }19 20     private void BindeList()//第一次加载21     {22       if (!Page.IsPostBack)23       {24         Bindlist2();25       }26     }27 28     private void Bindlist2()29     {30       string sql = "select * from student";31       string strcon = "server=DESKTOP-QQGOIKH;database=stuDB;uid=sa;pwd=123";32       SqlConnection sqlcon = new SqlConnection(strcon);33       //创建适配器实例,在dataset与数据之间架起桥梁作用34       SqlDataAdapter myda = new SqlDataAdapter(sql, sqlcon);35       //创建dataset实例数据集36       DataSet myds = new DataSet();37       //打开数据库38       sqlcon.Open();39       //将表填充到数据集40       myda.Fill(myds, "staff");41       GridView1.DataSource = myds;42       GridView1.DataKeyNames = new string[] { "stuID" };43       GridView1.DataBind();44     }45 46     //编辑47     protected void Button2_Click(object sender, EventArgs e)48     {49      50         //sender代表button内容51         Button bt = sender as Button;//尝试sender转换为button类型,如果无法转换,将返回一个空值52         string id = bt.CommandArgument;53         Response.Redirect("updateLinst.aspx?id=" + id);54      55     }56     //删除57     protected void Button3_Click(object sender, EventArgs e)58     {59       //多项删除60       int count = 0;//计数器61       //遍历griview62       foreach (GridViewRow item in GridView1.Rows)//foreach不能直接遍历gridview,只能遍历行的集合63       {64         CheckBox cb = item.Cells[0].FindControl("CheckBox2") as CheckBox;//sender as CheckBox错误65         //获取每一行第一列的服务器控件为checkBo2的内容66         if (cb.Checked)67         {68           HiddenField hf = item.Cells[0].FindControl("HiddenField1") as HiddenField;69           string id = hf.Value;70           string sql = "delete from student where stuID=@a";71           SqlParameter pms = new SqlParameter("@a", id);72           SqlConnection conn = new SqlConnection("server=DESKTOP-QQGOIKH;database=stuDB;uid=sa;pwd=123");73           conn.Open();74           SqlCommand cmd = new SqlCommand(sql, conn);75           cmd.Parameters.Add(pms);76           int i = cmd.ExecuteNonQuery();77           count += i;78           conn.Close();79         }80       }81       if (count > 0)82       {83         Response.Write("一共删除了"+count+"条数据");84         Bindlist2();85       }86       else87       {88         Response.Write("删除失败");89       }90     }91 92     protected void Button4_Click(object sender, EventArgs e)93     {94       Response.Redirect("insertList.aspx");95     }96   }97 }

Index后台
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="updateLinst.aspx.cs" Inherits="WebApplication1.updateLinst" %> 2  3 <!DOCTYPE html> 4  5 <html "http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8   <title></title> 9 </head>10 <body>11   <form id="form1" runat="server">12   <div>13     <asp:Label ID="Label1" runat="server" Text="姓名"></asp:Label> 14     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>15     <br />16     <asp:Label ID="Label2" runat="server" Text="编号"></asp:Label> 17     <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>18     <br />19     <asp:Label ID="Label3" runat="server" Text="学号"></asp:Label> 20     <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>21     <br />22     <asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />23     <asp:Button ID="Button2" runat="server" Text="返回" OnClick="Button2_Click" />24   </div>25   </form>26 </body>27 </html>

修改页面
 1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Data.SqlClient; 5 using System.Linq; 6 using System.Web; 7 using System.Web.UI; 8 using System.Web.UI.WebControls; 9 10 namespace WebApplication111 {12   public partial class updateLinst : System.Web.UI.Page13   {14     string strcon = "server=DESKTOP-QQGOIKH;database=stuDB;uid=sa;pwd=123";15     protected void Page_Load(object sender, EventArgs e)16     {17       if (!Page.IsPostBack)18       {19         string id = Request["id"].ToString();20         //取stuID对应的数据21         string sql = "select * from student where stuID=@a";22         SqlParameter pms = new SqlParameter("@a", id);23         //ADO.NET操作24         SqlConnection conn = new SqlConnection(strcon);25         conn.Open();26         SqlCommand cmd = new SqlCommand(sql, conn);27         //传入参数28         cmd.Parameters.Add(pms);29         //执行30         SqlDataReader sdr = cmd.ExecuteReader();31         //读取32         bool b = sdr.Read();//b代表是否读取到数据33         if (b==true)34         {35           TextBox1.Text = sdr["stuName"].ToString();36           TextBox2.Text = sdr["stuNo"].ToString();37           TextBox3.Text = sdr["sex"].ToString();38         }39         conn.Close();40       }41       42 43     }44     //提交45     protected void Button1_Click(object sender, EventArgs e)46     {47       //取到id48       string id = Request["id"];49       string sql = "update student set stuName=@b,stuNo=@c,sex=@d where stuID=@a";50 51       SqlParameter[] pms = new SqlParameter[4];52       pms[0] = new SqlParameter("@a", id);53       pms[1] = new SqlParameter("@b", TextBox1.Text);54       pms[2] = new SqlParameter("@c", TextBox2.Text);55       pms[3] = new SqlParameter("@d", TextBox3.Text);56       //ADO.NET操作57       SqlConnection conn = new SqlConnection(strcon);58       conn.Open();59       SqlCommand cmd = new SqlCommand(sql, conn);60       cmd.Parameters.Add(pms[0]);61       cmd.Parameters.Add(pms[1]);62       cmd.Parameters.Add(pms[2]);63       cmd.Parameters.Add(pms[3]);64       int i = cmd.ExecuteNonQuery();65       conn.Close();66       if (i>0)67       {68         Response.Write("修改成功");69       }70       else71       {72         Response.Write("修改失败");73       }74     }75     //返回76     protected void Button2_Click(object sender, EventArgs e)77     {78       Response.Redirect("Index.aspx");79     }80   }81 }

修改后台
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="insertList.aspx.cs" Inherits="WebApplication1.insertList" %> 2  3 <!DOCTYPE html> 4  5 <html "http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8   <title></title> 9 </head>10 <body>11   <form id="form1" runat="server">12   <div>13   14     <asp:Label ID="Label1" runat="server" Text="姓名"></asp:Label>15     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>16     <br />17     <asp:Label ID="Label2" runat="server" Text="学号"></asp:Label>18     <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>19     <br />20     <asp:Label ID="Label3" runat="server" Text="性别"></asp:Label>21     <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>22     <br />23     <asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />24   </div>25   </form>26 </body>27 </html>

新增页面
 1 using System; 2 using System.Collections.Generic; 3 using System.Data.SqlClient; 4 using System.Linq; 5 using System.Web; 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8  9 namespace WebApplication110 {11   public partial class insertList : System.Web.UI.Page12   {13     protected void Page_Load(object sender, EventArgs e)14     {15 16     }17     //新增提交18     protected void Button1_Click(object sender, EventArgs e)19     {20       21       string sql = "insert into student (stuName, stuNo,sex) values (@a, @b,@c)";22       string strcon = "server=DESKTOP-QQGOIKH;database=stuDB;uid=sa;pwd=123";23       SqlParameter[] pms = new SqlParameter[3];24       pms[0] = new SqlParameter("@a", TextBox1.Text);25       pms[1] = new SqlParameter("@b", TextBox2.Text);26       pms[2] = new SqlParameter("@c", TextBox3.Text);27       //ADO.NET操作28       SqlConnection conn = new SqlConnection(strcon);29       conn.Open();30       SqlCommand cmd = new SqlCommand(sql, conn);31       cmd.Parameters.Add(pms[0]);32       cmd.Parameters.Add(pms[1]);33       cmd.Parameters.Add(pms[2]);34       int i = cmd.ExecuteNonQuery();35       conn.Close();36       if (i > 0)37       {38         Response.Write("添加成功");39         Response.Redirect("index.aspx");40       }41       else42       {43         Response.Write("添加失败");44       }45     }46   }47 }

新增后台