- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <%--若是有自定義的模板,不適用 自動生成字段 ,需 AutoGenerateColumns="False" --%>
- <%-- GridView 控件以控件狀態存儲這些鍵字段值。若是這些值包含敏感信息,則強烈建議您經過將 ViewStateEncryptionMode
- 屬性設置爲 ViewStateEncryptionMode.Always 來啓用視圖狀態加密。--%>
- <asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False"
- CellPadding="4" ForeColor="#333333" GridLines="None"
- onrowcancelingedit="gvStudent_RowCancelingEdit"
- onrowdatabound="gvStudent_RowDataBound" onrowdeleting="gvStudent_RowDeleting"
- onrowediting="gvStudent_RowEditing" onrowupdating="gvStudent_RowUpdating"
- onselectedindexchanging="gvStudent_SelectedIndexChanging"
- onpageindexchanging="gvStudent_PageIndexChanging" DataKeyNames="id">
- <RowStyle BackColor="#EFF3FB" />
- <%--DataKeyNames 一個數組,包含了顯示在gridview控件中的項的主鍵字段的名字。
- 指定表示數據源主鍵的字段,爲了是gridview控件的自動更新和刪除功能,必須設置datakeynames="主鍵"。
- 爲了指定要更新或刪除的行,這些鍵字段的值被傳遞到數據源控件。
- 當設置了datakeynames屬性時,gridview控件用來自指定字段的值填充它的datakeys集合,提供了一種
- 訪問每一個行的主鍵的便捷方法。--%>
- <%-- 在使用自動生成的字段列時(經過將 AutoGenerateColumns 屬性設置爲 true),GridView 控件確保與 DataKeyNames 屬性中指定的字段相對應的列是隻讀的。--%>
- <%--若是將某個列字段的 Visible 屬性設置爲 false,則在 GridView 控件中將不顯示該列,該列中的數據也不會往返於客戶端。若是但願某個不可見的列中的數據能夠供客戶端使用,則向 DataKeyNames 屬性添加相應的字段名稱。--%>
- <%--標記中的 GridView 元素的 DataKeyNames 特性經過使用逗號分隔名稱來指定兩個鍵字段--%>
- <Columns>
- <asp:BoundField HeaderText="編號" Visible="false" DataField="id"/>
- <asp:TemplateField HeaderText ="姓名">
- <ItemTemplate>
- <%#Eval("name")%>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:textbox ID ="TBName" Text='<%#Eval("name") %>' runat="server">'>
- </asp:textbox>
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="性別">
- <ItemTemplate>
- <%#Eval("sex").Equals(true) ? "男" : "女"%><%--性別是bit類型,顯示應該爲(男、女)--%>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:DropDownList ID="DDLSex" runat="server" Width="90px" AutoPostBack="false"/><%--AutoPostBack="false" 不回發--%>
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="班級">
- <ItemTemplate>
- <%#Eval("class") %>
- </ItemTemplate>
- <EditItemTemplate>
- <%-- <asp:HiddenField ID="HDFClass" runat="server" Value='<%# Eval("classID") %>' />--%><%--當dropdownlist 綁定數據源,需顯示name,同事需對classID進行操做時,能夠用hiddenField保存classID的值--%>
- <asp:DropDownList ID="DDLClass" runat="server" Width="90px" /><%-- class 可更改,dropdownlist 供選擇--%>
- </EditItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="成績">
- <ItemTemplate>
- <%#Eval("grade")%>
- </ItemTemplate>
- <EditItemTemplate>
- <asp:textbox ID ="TBGrade" Text='<%#Eval("grade") %>' runat="server">'> <%--若grade可更改,簽入textbox--%>
- </asp:textbox>
- </EditItemTemplate>
- </asp:TemplateField>
- <%-- <asp:BoundField HeaderText="成績" DataField="grade" ReadOnly="true" /> --%> <%--若grade列不可改,只需這樣寫--%>
- <asp:BoundField HeaderText ="創建時間" DataField="createtime" ReadOnly="true" />
- <asp:CommandField ShowDeleteButton="true" ShowEditButton="true" HeaderText="操做" />
- </Columns>
- <PagerSettings FirstPageText="" LastPageText="" NextPageText="" PreviousPageText="" />
- <RowStyle Height="20px" BackColor="#F7F6F3" ForeColor="#333333" />
- <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
- <EditRowStyle BackColor="#999999" />
- <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
- <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
- <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
- <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
- </asp:GridView>
- </div>
- </form>
- </body>
- </html>
C# 代碼html
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.Data;
- using System.Data.Common;
- using System.Collections;
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if(!IsPostBack)//首次加載和訪問,ispostback=true 表示爲相應客戶端回發而加載
- GridViewBind();
- }
- protected void gvStudent_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
- {
- }
- protected void gvStudent_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
- //綁定班級
- if (((DropDownList)e.Row.FindControl("DDLClass")) != null)
- {
- DropDownList ddlclass = (DropDownList)e.Row.FindControl("DDLClass");
- //生成dropdownlist 的值,綁定數據
- string sqlStr = "select distinct(class) from student";
- DataSet ds = new DataSet();
- SqlConnection conn = new SqlConnection(StrConn);
- conn.Open();
- SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
- da.Fill(ds,"class");
- conn.Close();
- ArrayList alClass = new ArrayList();
- for (int i = 0; i < ds.Tables["class"].Rows.Count; i++)
- {
- alClass.Add(ds.Tables["class"].Rows[i]["class"]);
- }
- ddlclass.DataSource = alClass;//從庫中獲取數據
- ddlclass.DataBind();
- }
- //綁定性別
- if (((DropDownList)e.Row.FindControl("DDLSex")) != null)
- {
- DropDownList ddlsex = (DropDownList)e.Row.FindControl("DDLSex");
- ArrayList al = new ArrayList();
- al.Add("女"); // 索引 0
- al.Add("男"); //索引 1
- ddlsex.DataSource = al; //dropdownlist的另外一數據源(自定義數據
- ddlsex.DataBind();
- }
- }
- protected void gvStudent_RowEditing(object sender, GridViewEditEventArgs e)
- {
- gvStudent.EditIndex = e.NewEditIndex;//所編輯行的索引
- GridViewBind();
- }
- protected void gvStudent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
- {
- gvStudent.EditIndex = -1;
- GridViewBind();
- }
- protected void gvStudent_RowUpdating(object sender, GridViewUpdateEventArgs e)
- {
- string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
- try
- {
- //如下三種方式獲取 Id,前提是確保datakeynames="id"
- // 2. string id = gvStudent.DataKeys[e.RowIndex].Values[0].ToString();
- // 1. string id = gvStudent.DataKeys[e.RowIndex].Value.ToString();
- string id = ((GridView)sender).DataKeys[e.RowIndex].Values["id"].ToString();//DataKeys gridview控件中每一行的數據鍵值
- string name = ((TextBox)gvStudent.Rows[e.RowIndex].FindControl("TBName")).Text;
- int sex = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedIndex;//選定項的索引 0
- //string sexs1 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedItem.ToString();//索引最小的選定項 男
- //string sexs2 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).SelectedValue.ToString();//選定項的值 男
- //string sex3 = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLSex")).Text;//選定項的text 男
- string className = ((DropDownList)gvStudent.Rows[e.RowIndex].FindControl("DDLClass")).SelectedValue;
- string grade = ((TextBox)gvStudent.Rows[e.RowIndex].FindControl("TBGrade")).Text;
- DateTime updatetime = DateTime.Now;
- SqlConnection conn = new SqlConnection(StrConn);
- conn.Open();
- string sql = "update student set name='" + name + "',sex=" + sex + ",class='" + className + "',createtime='" + updatetime + "',grade='"+grade+"' where id=" + id; //grade可改時的sql
- // string sql = "update student set name='" + name + "',sex=" + sex + ",class='" + className + "',createtime='" + updatetime + "' where id=" + id;// grade 不可改時的sql
- SqlCommand cmd = new SqlCommand(sql, conn);
- cmd.ExecuteNonQuery();
- cmd.Dispose();
- if (conn.State.ToString() == "open")
- conn.Close();
- gvStudent.EditIndex = -1;
- GridViewBind();
- }
- catch (Exception ex)
- {
- Response.Write("數據庫錯誤,錯誤緣由:" + ex.Message);
- Response.End();
- }
- }
- protected void gvStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
- {
- string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString();
- string id = gvStudent.DataKeys[e.RowIndex].Values[0].ToString();
- string sql = "delete from student where id="+id ;
- try
- {
- SqlConnection conn = new SqlConnection(StrConn);
- if (conn.State.ToString() == "Closed") conn.Open();
- SqlCommand comm = new SqlCommand(sql, conn);
- comm.ExecuteNonQuery();
- comm.Dispose();
- if (conn.State.ToString() == "Open") conn.Close();
- gvStudent.EditIndex = -1;
- GridViewBind();
- }
- catch (Exception ex)
- {
- Response.Write("數據庫錯誤,錯誤緣由:" + ex.Message);
- Response.End();
- }
- }
- private void GridViewBind()
- {
- string StrConn = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString(); //在web.config中定義過了connectionString
- // 或 string StrConn = "Data Source=LENOVO-THINK\\FMSQLSERVERR2;Initial Catalog=MyTest;Integrated Security=True"; //webconfig 中未定義,直接在C# 代碼中寫鏈接字符串
- string sqlStr = "select * from student";
- DataSet ds = new DataSet();
- try
- {
- SqlConnection conn = new SqlConnection(StrConn);
- conn.Open();
- SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
- da.Fill(ds);
- conn.Close();
- DataTable tb = ds.Tables[0];
- gvStudent.DataSource = tb;
- gvStudent.DataBind();
- }
- catch (Exception ex)
- {
- Response.Write("數據庫錯誤,錯誤緣由:"+ex.Message);
- Response.End();
- }
- }
- protected void gvStudent_PageIndexChanging(object sender, GridViewPageEventArgs e)
- {
- gvStudent.PageIndex = e.NewPageIndex;//當前顯示頁的索引
- GridViewBind();
- }
- }