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. 【SpringMVC】使用SpringMVC进行上传文件!

    写在前面: 之前在上传文件的时候,使用的是commons-file-upload这个插件,非常方便,能控制每个文件的大小,总共大小,缓存,以及支持多个文件的同时上传,但是写一次上传文件的后台代码量太大 ...

  2. 暑假集训D11总结

    %dalao 今天某学长来讲一个极其高深的数据结构——线段树(woc哪里高深了),然而并没有时间整理笔记= =,所以明天在扔笔记咯= = 考试 今天考试,一看数据范围,woc暴力分给的真足,然后高高兴 ...

  3. Alluxio 1.5集群搭建

    一.依赖文件安装 1.1 JDK 参见博文:http://www.cnblogs.com/liugh/p/6623530.html 二.文件准备 2.1 文件名称 alluxio-1.5.0-hado ...

  4. 【思维】【水】 南阳oj 喷水装置(一)

    描述 现有一块草坪,长为20米,宽为2米,要在横中心线上放置半径为Ri的喷水装置,每个喷水装置的效果都会让以它为中心的半径为实数Ri(0<Ri<15)的圆被湿润,这有充足的喷水装置i(1& ...

  5. HDU字符串基础题(1020,1039,1062,1088,1161,1200,2017)

    并不是很精简,随便改改A过了就没有再简化了. 1020. Problem Description Given a string containing only 'A' - 'Z', we could ...

  6. Modelsimse10.1如何编译altera库文件以支持IP仿真

    前言 se版本默认没有ip之类的库支持,如果你用到了pll之类的ip,仿真前就得把库编译好. 流程 本例用的是altera的verilog库. 1.首先在modelsim安装目录下新建altera文件 ...

  7. 理清JS数组、json、js对象的区别与联系

    最近在敲代码时,遇上了一个关于JS数组的问题,由此引发了关于对象和json的联想,曾经觉得很畅顺的知识点突然模糊了.于是,为了理清这些东西,有了如下这篇文章.觉得没问题的猿们可以当复习,而那些带着疑问 ...

  8. 解决:wordpress error establishing a database connection problem

    我是个网站菜鸟,刚开始搭建LAMP环境的时候,就要了我半条老命. 没办法,懂的东西太少,LAMP是什么我都不懂,域名是什么,我也被不懂,为什么想要有个网站就要有服务器我还是不懂.一步步地自己去钻,去看 ...

  9. 剑指OFFER——顺时针打印矩阵

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8 ...

  10. Vue多元素过渡

    前面的话 前面分别介绍了单元素过渡的CSS过渡和JS过渡,本文将详细介绍Vue多元素过渡 常见示例 最常见的多标签过渡是一个列表和描述这个列表为空消息的元素: <transition> & ...