-
前台页面:
Default.aspx
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8 <title>GridView用法</title> 9 </head> 10 <body> 11 <form id="form1" runat="server"> 12 <div> 13 <asp:GridView ID="gvUserInfo" runat="server" AllowPaging="True" PageSize="4" OnSorting="gvUserInfo_Sorting" AllowSorting="true" AutoGenerateEditButton="true" OnRowDataBound="gvUserInfo_RowDataBound" OnRowEditing="gvUserInfo_RowEditing" OnRowUpdating="gvUserInfo_RowUpdating" OnRowCancelingEdit="gvUserInfo_RowCancelingEdit" OnPageIndexChanging="gvUserInfo_PageIndexChanging" OnRowDeleting="gvUserInfo_RowDeleting" EnableModelValidation="True" CellPadding="4" ForeColor="#333333" GridLines="None" > 14 <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> 15 <Columns> 16 <%-- !!! DataNavigateUrlFields属性是获取或设置数据源中字段的名称,用于为其超链接构造URL,其字段名称应为GridView中的数据字段名 17 --%> 18 19 <asp:HyperLinkField NavigateUrl="Info.aspx" DataNavigateUrlFields="用户编号" DataNavigateUrlFormatString="Info.aspx?userId={0}" Target="_blank" Text="详细信息"/> 20 <asp:TemplateField> 21 <ItemTemplate> 22 <asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="删除" CausesValidation="false" OnClientClick="return confirm('确定删除?')" > 23 </asp:Button> 24 </ItemTemplate> 25 </asp:TemplateField> 26 </Columns> 27 <EditRowStyle BackColor="#999999" /> 28 <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 29 <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 30 <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 31 <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> 32 <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 33 </asp:GridView> 34 </div> 35 </form> 36 </body> 37 </html>
info.aspx
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="info.aspx.cs" Inherits="info" %> 2 3 <!DOCTYPE html> 4 5 <html xmlns="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:Table runat="server" Caption="用户信息" > 14 <asp:TableRow> 15 <asp:TableCell>用户编号:</asp:TableCell> 16 <asp:TableCell> 17 <asp:Label ID="lblUserId" runat="server" Text=""></asp:Label></asp:TableCell> 18 </asp:TableRow> 19 <asp:TableRow> 20 <asp:TableCell>性别:</asp:TableCell> 21 <asp:TableCell><asp:Label ID="lblSex" runat="server" Text=""></asp:Label></asp:TableCell> 22 </asp:TableRow> 23 <asp:TableRow> 24 <asp:TableCell>邮箱:</asp:TableCell> 25 <asp:TableCell><asp:Label ID="lblMail" runat="server" Text=""></asp:Label></asp:TableCell> 26 </asp:TableRow> 27 </asp:Table> 28 <asp:Button ID="btnExit" runat="server" Text="关闭窗口" OnClientClick="javascript:window.opener=null;window.close();"/> 29 </div> 30 </form> 31 </body> 32 </html>
-
后台页面:
Default.aspx.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 using System.Web.UI; 5 using System.Web.UI.WebControls; 6 using System.Data; 7 using System.Data.SqlClient; 8 9 public partial class _Default : System.Web.UI.Page 10 { 11 protected void Page_Load(object sender, EventArgs e) 12 { 13 if (!IsPostBack) 14 { 15 ViewState["SortOrder"] = "用户编号"; 16 ViewState["OrderDir"] = "DESC"; 17 dataBind(); 18 } 19 } 20 21 /// <summary> 22 /// 绑定数据库中的数据到GridView控件中 23 /// </summary> 24 protected void dataBind() 25 { 26 string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ToString(); 27 SqlConnection conn = new SqlConnection(conStr); 28 if (conn.State == ConnectionState.Closed) 29 { 30 conn.Open(); 31 } 32 // string strSql = "select userId,userName from tabUserInfo"; 33 string strSql = "select userId as 用户编号,userName as 用户名 from tabUserInfo"; 34 SqlDataAdapter da = new SqlDataAdapter(strSql, conn); 35 DataSet ds = new DataSet(); 36 da.Fill(ds, "tabUserInfo"); 37 38 string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDir"]; 39 DataView view = ds.Tables["tabUserInfo"].DefaultView; 40 view.Sort = sort; 41 42 gvUserInfo.DataSource = view; 43 gvUserInfo.DataKeyNames = new string[]{"用户编号"}; 44 gvUserInfo.DataBind(); 45 46 //对特定数据用特定的显示方式 47 for (int i = 0; i < gvUserInfo.Rows.Count; i++) 48 { 49 DataRowView myDrv = ds.Tables["tabUserInfo"].DefaultView[i]; 50 string id = myDrv["用户编号"].ToString(); 51 if (Convert.ToInt32(id) < 5) 52 { 53 gvUserInfo.Rows[i].Cells[4].BackColor = System.Drawing.Color.Red; 54 } 55 } 56 if (conn.State == ConnectionState.Open) 57 { 58 conn.Close(); 59 } 60 } 61 62 /// <summary> 63 /// 实现分页功能 64 /// </summary> 65 /// <param name="sender"></param> 66 /// <param name="e"></param> 67 protected void gvUserInfo_PageIndexChanging(object sender, GridViewPageEventArgs e) 68 { 69 gvUserInfo.PageIndex = e.NewPageIndex; 70 dataBind(); 71 } 72 73 74 /// <summary> 75 /// 删除GridView中数据 76 /// </summary> 77 /// <param name="sender"></param> 78 /// <param name="e"></param> 79 protected void gvUserInfo_RowDeleting(object sender, GridViewDeleteEventArgs e) 80 { 81 SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ToString()); 82 string strSql = "delete from tabUserInfo where userId=" +gvUserInfo.DataKeys[e.RowIndex].Value.ToString()+ ""; 83 conn.Open(); 84 SqlCommand cmd = new SqlCommand(strSql, conn); 85 if (cmd.ExecuteNonQuery() > 0) 86 Response.Write("<script>alert('删除成功!')</script>"); 87 else 88 Response.Write("<script>alert('删除失败!')</script>"); 89 conn.Close(); 90 dataBind(); 91 } 92 /// <summary> 93 /// 编辑GridView中的数据 94 /// </summary> 95 /// <param name="sender"></param> 96 /// <param name="e"></param> 97 protected void gvUserInfo_RowEditing(object sender, GridViewEditEventArgs e) 98 { 99 gvUserInfo.EditIndex = e.NewEditIndex; 100 dataBind(); 101 } 102 /// <summary> 103 ///更改数据并提交到数据库 104 /// </summary> 105 /// <param name="sender"></param> 106 /// <param name="e"></param> 107 protected void gvUserInfo_RowUpdating(object sender, GridViewUpdateEventArgs e) 108 { 109 string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ToString(); 110 SqlConnection conn = new SqlConnection(conStr); 111 string strSql = "update tabUserInfo set userName='" + ((TextBox)(gvUserInfo.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim() + "' where userId=" + gvUserInfo.DataKeys[e.RowIndex].Value.ToString() + ""; 112 // 113 conn.Open(); 114 SqlCommand cmd = new SqlCommand(strSql, conn); 115 cmd.ExecuteNonQuery(); 116 Response.Write("<script>alert('更改成功!')</script>"); 117 conn.Close(); 118 gvUserInfo.EditIndex = -1; 119 dataBind(); 120 } 121 /// <summary> 122 /// 取消对GridView中数据的编辑 123 /// </summary> 124 /// <param name="sender"></param> 125 /// <param name="e"></param> 126 protected void gvUserInfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) 127 { 128 gvUserInfo.EditIndex = -1; 129 dataBind(); 130 } 131 /// <summary> 132 /// RowDataBound事件 133 /// </summary> 134 /// <param name="sender"></param> 135 /// <param name="e"></param> 136 protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e) 137 { 138 //高亮显示鼠标指定行数据 139 if (e.Row.RowType == DataControlRowType.DataRow) 140 { 141 e.Row.Attributes.Add("onMouseOver", "Color=this.style.backgroundColor;this.style.backgroundColor='lightblue'"); 142 e.Row.Attributes.Add("onMouseOut", "this.style.backgroundColor=Color;"); 143 } 144 } 145 /// <summary> 146 /// 排序代码 147 /// </summary> 148 /// <param name="sender"></param> 149 /// <param name="e"></param> 150 protected void gvUserInfo_Sorting(object sender, GridViewSortEventArgs e) 151 { 152 string strPage = e.SortExpression; 153 if (ViewState["SortOrder"].ToString() == strPage) 154 { 155 if (ViewState["OrderDir"].ToString() == "DESC") 156 { 157 ViewState["OrderDir"] = "ASC"; 158 } 159 else 160 { 161 ViewState["OrderDir"] = "DESC"; 162 } 163 } 164 else 165 { 166 ViewState["SortOrder"] = e.SortExpression; 167 } 168 dataBind(); 169 } 170 }
info.aspx.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 using System.Web.UI; 5 using System.Web.UI.WebControls; 6 using System.Data; 7 using System.Data.SqlClient; 8 9 public partial class info : System.Web.UI.Page 10 { 11 protected void Page_Load(object sender, EventArgs e) 12 { 13 if (!IsPostBack) 14 { 15 dataBind(); 16 } 17 } 18 19 protected void dataBind() 20 { 21 string conStr=System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ToString(); 22 SqlConnection conn = new SqlConnection(conStr); 23 if (conn.State == ConnectionState.Closed) 24 { 25 conn.Open(); 26 } 27 string strSql = "select * from tabUserInfo where userId="+Request["userId"].ToString()+";"; 28 SqlDataAdapter da = new SqlDataAdapter(strSql, conn); 29 DataSet ds = new DataSet(); 30 da.Fill(ds, "tabInfo"); 31 DataRowView rowView = ds.Tables["tabInfo"].DefaultView[0]; 32 lblUserId.Text = Convert.ToString(rowView["userId"]); 33 lblSex.Text = Convert.ToString(rowView["userSex"]); 34 lblMail.Text = Convert.ToString(rowView["userMail"]); 35 36 if (conn.State == ConnectionState.Open) 37 { 38 conn.Close(); 39 } 40 } 41 }