-
前台页面:
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>GridView用法</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvUserInfo" runat="server" AllowPaging="True" PageSize="" 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="" ForeColor="#333333" GridLines="None" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<%-- !!! DataNavigateUrlFields属性是获取或设置数据源中字段的名称,用于为其超链接构造URL,其字段名称应为GridView中的数据字段名
--%> <asp:HyperLinkField NavigateUrl="Info.aspx" DataNavigateUrlFields="用户编号" DataNavigateUrlFormatString="Info.aspx?userId={0}" Target="_blank" Text="详细信息"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="删除" CausesValidation="false" OnClientClick="return confirm('确定删除?')" >
</asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</div>
</form>
</body>
</html>
info.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="info.aspx.cs" Inherits="info" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>用户详细信息</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Table runat="server" Caption="用户信息" >
<asp:TableRow>
<asp:TableCell>用户编号:</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblUserId" runat="server" Text=""></asp:Label></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>性别:</asp:TableCell>
<asp:TableCell><asp:Label ID="lblSex" runat="server" Text=""></asp:Label></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>邮箱:</asp:TableCell>
<asp:TableCell><asp:Label ID="lblMail" runat="server" Text=""></asp:Label></asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:Button ID="btnExit" runat="server" Text="关闭窗口" OnClientClick="javascript:window.opener=null;window.close();"/>
</div>
</form>
</body>
</html>
-
后台页面:
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["SortOrder"] = "用户编号";
ViewState["OrderDir"] = "DESC";
dataBind();
}
} /// <summary>
/// 绑定数据库中的数据到GridView控件中
/// </summary>
protected void dataBind()
{
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ToString();
SqlConnection conn = new SqlConnection(conStr);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
// string strSql = "select userId,userName from tabUserInfo";
string strSql = "select userId as 用户编号,userName as 用户名 from tabUserInfo";
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "tabUserInfo"); string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDir"];
DataView view = ds.Tables["tabUserInfo"].DefaultView;
view.Sort = sort; gvUserInfo.DataSource = view;
gvUserInfo.DataKeyNames = new string[]{"用户编号"};
gvUserInfo.DataBind(); //对特定数据用特定的显示方式
for (int i = ; i < gvUserInfo.Rows.Count; i++)
{
DataRowView myDrv = ds.Tables["tabUserInfo"].DefaultView[i];
string id = myDrv["用户编号"].ToString();
if (Convert.ToInt32(id) < )
{
gvUserInfo.Rows[i].Cells[].BackColor = System.Drawing.Color.Red;
}
}
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
} /// <summary>
/// 实现分页功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvUserInfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvUserInfo.PageIndex = e.NewPageIndex;
dataBind();
} /// <summary>
/// 删除GridView中数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvUserInfo_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ToString());
string strSql = "delete from tabUserInfo where userId=" +gvUserInfo.DataKeys[e.RowIndex].Value.ToString()+ "";
conn.Open();
SqlCommand cmd = new SqlCommand(strSql, conn);
if (cmd.ExecuteNonQuery() > )
Response.Write("<script>alert('删除成功!')</script>");
else
Response.Write("<script>alert('删除失败!')</script>");
conn.Close();
dataBind();
}
/// <summary>
/// 编辑GridView中的数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvUserInfo_RowEditing(object sender, GridViewEditEventArgs e)
{
gvUserInfo.EditIndex = e.NewEditIndex;
dataBind();
}
/// <summary>
///更改数据并提交到数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvUserInfo_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ToString();
SqlConnection conn = new SqlConnection(conStr);
string strSql = "update tabUserInfo set userName='" + ((TextBox)(gvUserInfo.Rows[e.RowIndex].Cells[].Controls[])).Text.ToString().Trim() + "' where userId=" + gvUserInfo.DataKeys[e.RowIndex].Value.ToString() + "";
//
conn.Open();
SqlCommand cmd = new SqlCommand(strSql, conn);
cmd.ExecuteNonQuery();
Response.Write("<script>alert('更改成功!')</script>");
conn.Close();
gvUserInfo.EditIndex = -;
dataBind();
}
/// <summary>
/// 取消对GridView中数据的编辑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvUserInfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvUserInfo.EditIndex = -;
dataBind();
}
/// <summary>
/// RowDataBound事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
//高亮显示鼠标指定行数据
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onMouseOver", "Color=this.style.backgroundColor;this.style.backgroundColor='lightblue'");
e.Row.Attributes.Add("onMouseOut", "this.style.backgroundColor=Color;");
}
}
/// <summary>
/// 排序代码
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvUserInfo_Sorting(object sender, GridViewSortEventArgs e)
{
string strPage = e.SortExpression;
if (ViewState["SortOrder"].ToString() == strPage)
{
if (ViewState["OrderDir"].ToString() == "DESC")
{
ViewState["OrderDir"] = "ASC";
}
else
{
ViewState["OrderDir"] = "DESC";
}
}
else
{
ViewState["SortOrder"] = e.SortExpression;
}
dataBind();
}
}
info.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient; public partial class info : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dataBind();
}
} protected void dataBind()
{
string conStr=System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ToString();
SqlConnection conn = new SqlConnection(conStr);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
string strSql = "select * from tabUserInfo where userId="+Request["userId"].ToString()+";";
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "tabInfo");
DataRowView rowView = ds.Tables["tabInfo"].DefaultView[];
lblUserId.Text = Convert.ToString(rowView["userId"]);
lblSex.Text = Convert.ToString(rowView["userSex"]);
lblMail.Text = Convert.ToString(rowView["userMail"]); if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}