1. 前台页面:

    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>
  1. 后台页面:

    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();
}
}
}

GridView用法详解的更多相关文章

  1. Asp.net中GridView使用详解(很全,很经典 转来的)

    Asp.net中GridView使用详解 效果图参考:http://hi.baidu.com/hello%5Fworld%5Fws/album/asp%2Enet中以gv开头的图片 l         ...

  2. Asp.net中GridView使用详解(引)【转】

    Asp.net中GridView使用详解(引) GridView无代码分页排序 GridView选中,编辑,取消,删除 GridView正反双向排序 GridView和下拉菜单DropDownList ...

  3. Asp.net中GridView使用详解(很全,很经典)

    http://blog.csdn.net/hello_world_wusu/article/details/4052844 Asp.net中GridView使用详解 效果图参考:http://hi.b ...

  4. C#中string.format用法详解

    C#中string.format用法详解 本文实例总结了C#中string.format用法.分享给大家供大家参考.具体分析如下: String.Format 方法的几种定义: String.Form ...

  5. @RequestMapping 用法详解之地址映射

    @RequestMapping 用法详解之地址映射 引言: 前段时间项目中用到了RESTful模式来开发程序,但是当用POST.PUT模式提交数据时,发现服务器端接受不到提交的数据(服务器端参数绑定没 ...

  6. linux管道命令grep命令参数及用法详解---附使用案例|grep

    功能说明:查找文件里符合条件的字符串. 语 法:grep [-abcEFGhHilLnqrsvVwxy][-A<显示列数>][-B<显示列数>][-C<显示列数>] ...

  7. mysql中event的用法详解

    一.基本概念mysql5.1版本开始引进event概念.event既“时间触发器”,与triggers的事件触发不同,event类似与linux crontab计划任务,用于时间触发.通过单独或调用存 ...

  8. CSS中伪类及伪元素用法详解

    CSS中伪类及伪元素用法详解   伪类的分类及作用: 注:该表引自W3School教程 伪元素的分类及作用: 接下来让博主通过一些生动的实例(之前的作业或小作品)来说明几种常用伪类的用法和效果,其他的 ...

  9. c++中vector的用法详解

    c++中vector的用法详解 vector(向量): C++中的一种数据结构,确切的说是一个类.它相当于一个动态的数组,当程序员无法知道自己需要的数组的规模多大时,用其来解决问题可以达到最大节约空间 ...

随机推荐

  1. Docker进阶使用1

    容器间共享文件 Docker 的容器和外部环境是相对隔离的,并且容器是一次性的,运行结束后并不会有任何的持久化的文件或者数据.所以当我们需要做应用数据的持久化,或者保留应用的日志文件时,我们需要用到 ...

  2. 对JavaScript闭包的理解

    闭包(closure)是Javascript语言的一个难点,也是它的特色,很多高级应用都要依靠闭包实现. 在开始了解闭包前我们必须要先理解JavaScript的变量作用域. 一.变量的作用域无非就是两 ...

  3. ES6中的Set和Map集合

    前面的话 在ES6标准制定以前,由于可选的集合类型有限,数组使用的又是数值型索引,因而经常被用于创建队列和栈.如果需要使用非数值型索引,就会用非数组对象创建所需的数据结构,而这就是Set集合与Map集 ...

  4. Java内存区域与对象创建过程

    一.java内存区域 Java虚拟机在执行Java程序的过程中会把它所管理的内存划分为若干个不同的数据区域.这些区域都有各自的用途,以及创建和销毁的时间,有的区域随着虚拟机进程的启动而存在,有的区域则 ...

  5. Linux常用命令和常见问题解决<------>第一章

    查看文件下面所有的隐藏目录:ls -al ~ ls -al ~ls -a -l ~可以发现三条命令执行结果是一致的,原因:因为ls为命令 后面的参数要以空格来区分,不论几个空格 shell都会视为一体 ...

  6. Vue2源码分析-逻辑梳理

    很久之前就看完vue1,但是太懒就一直没写博客,这次打算抽下懒筋先把自己看过了记录下来,否则等全部看完,估计又没下文了 看源码总需要抱着一个目的,否则就很难坚持下去,我并没做过vue的项目,我几乎很少 ...

  7. ES6学习目录

    前面的话 ES6是JavaScript语言的下一代标准,已经在 2015 年 6 月正式发布.它的目标,是使得 JavaScript 语言可以用来编写复杂的大型应用程序,成为企业级开发语言 为什么要学 ...

  8. oracle ORA-00604/ORA-01653

    问题描述: ORA-00604: error occurred at recursive SQL level 1ORA-01653: unable to extend table SYS.AUD$ b ...

  9. ios 监听TextField中内容

    @property (weak, nonatomic) IBOutlet UITextField *UserID; @property (weak, nonatomic) IBOutlet UITex ...

  10. NYOJ--86--set.find()--找球号(一)

    /* Name: NYOJ--86--找球号(一) Date: 20/04/17 14:45 Description: 理想很美好,现实很残酷,准备用字符串水过,结果TLE了 ╮(╯▽╰)╭ */ # ...