GridView 的更新删除、操做及例子详解(结合textbox 和dropdownlist)

 

  
  
  
  
  1. <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %> 
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml"> 
  6. <head runat="server"> 
  7.     <title></title> 
  8. </head> 
  9. <body> 
  10.     <form id="form1" runat="server"> 
  11.     <div> 
  12.      
  13.  <%--若是有自定义的模板,不适用 自动生成字段 ,需 AutoGenerateColumns="False" --%> 
  14.    
  15. <%-- GridView 控件以控件状态存储这些键字段值。若是这些值包含敏感信息,则强烈建议您经过将 ViewStateEncryptionMode   
  16.  属性设置为 ViewStateEncryptionMode.Always 来启用视图状态加密。--%> 
  17.    
  18.        <asp:GridView ID="gvStudent" runat="server"  AutoGenerateColumns="False"   
  19.             CellPadding="4" ForeColor="#333333" GridLines="None"   
  20.             onrowcancelingedit="gvStudent_RowCancelingEdit"   
  21.             onrowdatabound="gvStudent_RowDataBound" onrowdeleting="gvStudent_RowDeleting"   
  22.             onrowediting="gvStudent_RowEditing" onrowupdating="gvStudent_RowUpdating"   
  23.             onselectedindexchanging="gvStudent_SelectedIndexChanging"   
  24.             onpageindexchanging="gvStudent_PageIndexChanging" DataKeyNames="id"> 
  25.             <RowStyle BackColor="#EFF3FB" /> 
  26.               
  27.           <%--DataKeyNames 一个数组,包含了显示在gridview控件中的项的主键字段的名字。  
  28.           指定表示数据源主键的字段,为了是gridview控件的自动更新和删除功能,必须设置datakeynames="主键"。  
  29.           为了指定要更新或删除的行,这些键字段的值被传递到数据源控件。  
  30.           当设置了datakeynames属性时,gridview控件用来自指定字段的值填充它的datakeys集合,提供了一种  
  31.           访问每一个行的主键的便捷方法。--%> 
  32.             
  33. <%-- 在使用自动生成的字段列时(经过将 AutoGenerateColumns 属性设置为 true),GridView 控件确保与 DataKeyNames 属性中指定的字段相对应的列是只读的。--%> 
  34. <%--若是将某个列字段的 Visible 属性设置为 false,则在 GridView 控件中将不显示该列,该列中的数据也不会往返于客户端。若是但愿某个不可见的列中的数据能够供客户端使用,则向 DataKeyNames 属性添加相应的字段名称。--%> 
  35. <%--标记中的 GridView 元素的 DataKeyNames 特性经过使用逗号分隔名称来指定两个键字段--%> 
  36.     <Columns> 
  37.     <asp:BoundField HeaderText="编号" Visible="false"  DataField="id"/>   
  38.          
  39.         <asp:TemplateField HeaderText ="姓名"> 
  40.         <ItemTemplate> 
  41.          <%#Eval("name")%> 
  42.         </ItemTemplate> 
  43.         <EditItemTemplate> 
  44.          <asp:textbox ID ="TBName" Text='<%#Eval("name") %>' runat="server">'> 
  45.          </asp:textbox> 
  46.         </EditItemTemplate> 
  47.         </asp:TemplateField>          
  48.      
  49.       <asp:TemplateField HeaderText="性别"> 
  50.          <ItemTemplate> 
  51.          <%#Eval("sex").Equals(true) ? "男" : "女"%><%--性别是bit类型,显示应该为(男、女)--%> 
  52.         </ItemTemplate>                
  53.         <EditItemTemplate>        
  54.            <asp:DropDownList ID="DDLSex" runat="server" Width="90px"  AutoPostBack="false"/><%--AutoPostBack="false" 不回发--%> 
  55.         </EditItemTemplate> 
  56.         </asp:TemplateField>          
  57.      
  58.         <asp:TemplateField HeaderText="班级"> 
  59.         <ItemTemplate> 
  60.         <%#Eval("class") %> 
  61.         </ItemTemplate> 
  62.         <EditItemTemplate> 
  63.         <%--   <asp:HiddenField ID="HDFClass" runat="server" Value='<%# Eval("classID") %>' />--%><%--当dropdownlist 绑定数据源,需显示name,同事需对classID进行操做时,能够用hiddenField保存classID的值--%> 
  64.            <asp:DropDownList ID="DDLClass" runat="server" Width="90px" /><%-- class 可更改,dropdownlist 供选择--%> 
  65.         </EditItemTemplate> 
  66.         </asp:TemplateField> 
  67.           
  68.        <asp:TemplateField HeaderText="成绩"> 
  69.         <ItemTemplate> 
  70.         <%#Eval("grade")%> 
  71.         </ItemTemplate> 
  72.         <EditItemTemplate> 
  73.          <asp:textbox ID ="TBGrade" Text='<%#Eval("grade") %>' runat="server">'> <%--若grade可更改,签入textbox--%> 
  74.          </asp:textbox> 
  75.         </EditItemTemplate> 
  76.         </asp:TemplateField> 
  77.        <%-- <asp:BoundField HeaderText="成绩" DataField="grade" ReadOnly="true" /> --%>  <%--若grade列不可改,只需这样写--%> 
  78.         <asp:BoundField HeaderText ="创建时间"  DataField="createtime"  ReadOnly="true" /> 
  79.         <asp:CommandField ShowDeleteButton="true" ShowEditButton="true" HeaderText="操做" /> 
  80.           
  81.            
  82.         </Columns>        
  83.               <PagerSettings FirstPageText="" LastPageText="" NextPageText="" PreviousPageText="" /> 
  84.                             <RowStyle Height="20px" BackColor="#F7F6F3" ForeColor="#333333" /> 
  85.                             <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
  86.                             <EditRowStyle BackColor="#999999" /> 
  87.                             <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 
  88.                             <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 
  89.                             <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
  90.                             <AlternatingRowStyle BackColor="White" ForeColor="#284775" />            
  91.         </asp:GridView> 
  92.     </div> 
  93.     </form> 
  94. </body> 
  95. </html> 

C# 代码html

 

  
  
  
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Configuration;  
  8. using System.Data.SqlClient;  
  9. using System.Data;  
  10. using System.Data.Common;  
  11. using System.Collections;  
  12.  
  13. public partial class _Default : System.Web.UI.Page   
  14. {  
  15.     protected void Page_Load(object sender, EventArgs e)  
  16.     {  
  17.         if(!IsPostBack)//首次加载和访问,ispostback=true 表示为相应客户端回发而加载  
  18.         GridViewBind();            
  19.     }  
  20.     protected void gvStudent_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)  
  21.     {  
  22.           
  23.           
  24.     }  
  25.     protected void gvStudent_RowDataBound(object sender, GridViewRowEventArgs e)  
  26.     {  
  27.         string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();  
  28.         //绑定班级  
  29.         if (((DropDownList)e.Row.FindControl("DDLClass")) != null)  
  30.         {  
  31.             DropDownList ddlclass = (DropDownList)e.Row.FindControl("DDLClass");  
  32.               
  33.             //生成dropdownlist 的值,绑定数据  
  34.             string sqlStr = "select distinct(class) from student";  
  35.             DataSet ds = new DataSet();  
  36.             SqlConnection conn = new SqlConnection(StrConn);  
  37.  
  38.             conn.Open();  
  39.             SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);  
  40.             da.Fill(ds,"class");  
  41.             conn.Close();     
  42.  
  43.             ArrayList alClass = new ArrayList();             
  44.               
  45.             for (int i = 0; i < ds.Tables["class"].Rows.Count; i++)  
  46.             {  
  47.                 alClass.Add(ds.Tables["class"].Rows[i]["class"]);  
  48.             }  
  49.                 ddlclass.DataSource = alClass;//从库中获取数据  
  50.                 ddlclass.DataBind();  
  51.         }  
  52.         //绑定性别  
  53.         if (((DropDownList)e.Row.FindControl("DDLSex")) != null)  
  54.         {  
  55.             DropDownList ddlsex = (DropDownList)e.Row.FindControl("DDLSex");  
  56.  
  57.             ArrayList al = new ArrayList();  
  58.             al.Add("女");  // 索引 0   
  59.             al.Add("男"); //索引 1  
  60.             ddlsex.DataSource = al;  //dropdownlist的另外一数据源(自定义数据  
  61.             ddlsex.DataBind();  
  62.         }  
  63.     }  
  64.     protected void gvStudent_RowEditing(object sender, GridViewEditEventArgs e)  
  65.     {  
  66.         gvStudent.EditIndex = e.NewEditIndex;//所编辑行的索引  
  67.         GridViewBind();  
  68.     }  
  69.     protected void gvStudent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  70.     {  
  71.         gvStudent.EditIndex = -1;  
  72.         GridViewBind();  
  73.     }  
  74.     protected void gvStudent_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  75.     {  
  76.         string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();  
  77.        try  
  78.        {  
  79.  
  80.            //如下三种方式获取 Id,前提是确保datakeynames="id" 
  81.           // 2. string id = gvStudent.DataKeys[e.RowIndex].Values[0].ToString();  
  82.           // 1. string id = gvStudent.DataKeys[e.RowIndex].Value.ToString();           
  83.             string id = ((GridView)sender).DataKeys[e.RowIndex].Values["id"].ToString();//DataKeys gridview控件中每一行的数据键值  
  84.             
  85.             string name = ((TextBox)gvStudent.Rows[e.RowIndex].FindControl("TBName")).Text;  
  86.             int sex = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedIndex;//选定项的索引  0  
  87.  
  88.             //string sexs1 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedItem.ToString();//索引最小的选定项 男  
  89.             //string sexs2 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedValue.ToString();//选定项的值 男  
  90.             //string sex3 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).Text;//选定项的text 男  
  91.              
  92.             string className = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLClass")).SelectedValue;  
  93.             string grade = ((TextBox)gvStudent.Rows[e.RowIndex].FindControl("TBGrade")).Text;  
  94.             DateTime updatetime = DateTime.Now;  
  95.  
  96.             SqlConnection conn = new SqlConnection(StrConn);  
  97.              
  98.             conn.Open();  
  99.  
  100.             string sql = "update student set name='" + name + "',sex=" + sex + ",class='" + className + "',createtime='" + updatetime + "',grade='"+grade+"'  where id=" + id; //grade可改时的sql  
  101.            // string sql = "update student set name='" + name + "',sex=" + sex + ",class='" + className + "',createtime='" + updatetime + "'  where id=" + id;// grade 不可改时的sql  
  102.  
  103.            SqlCommand cmd = new SqlCommand(sql, conn);  
  104.             cmd.ExecuteNonQuery();  
  105.             cmd.Dispose();  
  106.             if (conn.State.ToString() == "open")   
  107.                 conn.Close();  
  108.  
  109.             gvStudent.EditIndex = -1;  
  110.             GridViewBind();  
  111.         }  
  112.        catch (Exception ex)  
  113.        {  
  114.            Response.Write("数据库错误,错误缘由:" + ex.Message);  
  115.            Response.End();  
  116.        }  
  117.  
  118.     }  
  119.     protected void gvStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  120.     {  
  121.         string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();  
  122.  
  123.         string id = gvStudent.DataKeys[e.RowIndex].Values[0].ToString();  
  124.         string sql = "delete from student where id="+id ;  
  125.  
  126.         try  
  127.         {  
  128.             SqlConnection conn = new SqlConnection(StrConn);  
  129.             if (conn.State.ToString() == "Closed") conn.Open();  
  130.             SqlCommand comm = new SqlCommand(sql, conn);  
  131.             comm.ExecuteNonQuery();  
  132.             comm.Dispose();  
  133.             if (conn.State.ToString() == "Open") conn.Close();  
  134.  
  135.             gvStudent.EditIndex = -1;  
  136.             GridViewBind();  
  137.         }  
  138.         catch (Exception ex)  
  139.         {  
  140.             Response.Write("数据库错误,错误缘由:" + ex.Message);  
  141.             Response.End();  
  142.         }  
  143.  
  144.     }  
  145.  
  146.     private void GridViewBind()  
  147.     {   
  148.         string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();    //在web.config中定义过了connectionString  
  149.         // 或  string StrConn = "Data Source=LENOVO-THINK\\FMSQLSERVERR2;Initial Catalog=MyTest;Integrated Security=True";    //webconfig 中未定义,直接在C# 代码中写链接字符串  
  150.         string sqlStr = "select * from student";  
  151.         DataSet ds = new DataSet();  
  152.         try  
  153.         {  
  154.             SqlConnection conn = new SqlConnection(StrConn);  
  155.  
  156.             conn.Open();  
  157.             SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);  
  158.             da.Fill(ds);  
  159.             conn.Close();  
  160.             DataTable tb = ds.Tables[0];  
  161.  
  162.             gvStudent.DataSource = tb;  
  163.             gvStudent.DataBind();  
  164.         }  
  165.         catch (Exception ex)  
  166.         {  
  167.             Response.Write("数据库错误,错误缘由:"+ex.Message);  
  168.             Response.End();  
  169.         }  
  170.       
  171.     }  
  172.     protected void gvStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  173.     {  
  174.         gvStudent.PageIndex = e.NewPageIndex;//当前显示页的索引  
  175.         GridViewBind();  
  176.     }  
  177. }