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. 将Asp.Net Core和corefx移植到.Net 4.0

    引言 因为工作内容的原因需要兼容 XP,而 XP 最多支持到.Net Framework 4.0.因此无法享受到 .Net Core 带来的一堆很好用的库,好在无论 corefx 还是 Asp.Net ...

  2. Android源码博文集锦4

    Android精选源码 一款常见的自定义加载动画 android开源记账项目CoCoin Android自定义view:拖拽选择按钮 Android指纹识别 一个折线图,它提供了几个非常实用的功能 一 ...

  3. HDU1036 Average is not Fast Enough!

    Problem Description A relay is a race for two or more teams of runners. Each member of a team runs o ...

  4. Android学习笔记- ProgressBar(进度条)

    本节引言: 本节给大家带来的是Android基本UI控件中的ProgressBar(进度条),ProgressBar的应用场景很多,比如 用户登录时,后台在发请求,以及等待服务器返回信息,这个时候会用 ...

  5. Solr(二)Centos7 下solr-5.5.4核的创建

    solr核的创建 一 拷贝jar包 创建核需要一下两个Jar包,没有的话创建核会失败. (1)solr-dataimporthandler-5.3.1jar (2)solr-dataimporthan ...

  6. ThinkPHP5.0相关

    1.tp5的下载安装 使用git克隆下面的仓库地址,这个地址下载的速度比较快,差不多两分钟的时间. 克隆tp5的应用项目: git clone https://github.com/top-think ...

  7. 超超超简单的bfs——POJ-3278

    Catch That Cow Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 89836   Accepted: 28175 ...

  8. TFS build server搭建,搭建自动化构建服务器

    TFS build 服务器的搭建主要步骤如下: 一:环境准备: 新建一台build服务器 安装Visual Studio.主要目的是: a. 生成Build脚本所需要的build命令:b.与TFS组合 ...

  9. NYOJ116 士兵杀敌(二)

    士兵杀敌(二) 时间限制:1000 ms  |  内存限制:65535 KB 难度:5   描述 南将军手下有N个士兵,分别编号1到N,这些士兵的杀敌数都是已知的. 小工是南将军手下的军师,南将军经常 ...

  10. SEO配置信息操作文档

    一.title(网站标题) title,就是浏览器上显示的那些内容,不仅用户能看到,也能被搜索引擎检索到(搜索引擎在抓取网页时,最先读取的就是网页标题,所以title是否正确设置极其重要.)title ...