GridView用法详解
- 前台页面:
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();
}
}
}
GridView用法详解的更多相关文章
- Asp.net中GridView使用详解(很全,很经典 转来的)
Asp.net中GridView使用详解 效果图参考:http://hi.baidu.com/hello%5Fworld%5Fws/album/asp%2Enet中以gv开头的图片 l ...
- Asp.net中GridView使用详解(引)【转】
Asp.net中GridView使用详解(引) GridView无代码分页排序 GridView选中,编辑,取消,删除 GridView正反双向排序 GridView和下拉菜单DropDownList ...
- Asp.net中GridView使用详解(很全,很经典)
http://blog.csdn.net/hello_world_wusu/article/details/4052844 Asp.net中GridView使用详解 效果图参考:http://hi.b ...
- C#中string.format用法详解
C#中string.format用法详解 本文实例总结了C#中string.format用法.分享给大家供大家参考.具体分析如下: String.Format 方法的几种定义: String.Form ...
- @RequestMapping 用法详解之地址映射
@RequestMapping 用法详解之地址映射 引言: 前段时间项目中用到了RESTful模式来开发程序,但是当用POST.PUT模式提交数据时,发现服务器端接受不到提交的数据(服务器端参数绑定没 ...
- linux管道命令grep命令参数及用法详解---附使用案例|grep
功能说明:查找文件里符合条件的字符串. 语 法:grep [-abcEFGhHilLnqrsvVwxy][-A<显示列数>][-B<显示列数>][-C<显示列数>] ...
- mysql中event的用法详解
一.基本概念mysql5.1版本开始引进event概念.event既“时间触发器”,与triggers的事件触发不同,event类似与linux crontab计划任务,用于时间触发.通过单独或调用存 ...
- CSS中伪类及伪元素用法详解
CSS中伪类及伪元素用法详解 伪类的分类及作用: 注:该表引自W3School教程 伪元素的分类及作用: 接下来让博主通过一些生动的实例(之前的作业或小作品)来说明几种常用伪类的用法和效果,其他的 ...
- c++中vector的用法详解
c++中vector的用法详解 vector(向量): C++中的一种数据结构,确切的说是一个类.它相当于一个动态的数组,当程序员无法知道自己需要的数组的规模多大时,用其来解决问题可以达到最大节约空间 ...
随机推荐
- poj 1200 crasy search
https://vjudge.net/problem/POJ-1200 题意: 给出一个字符串,给出子串的长度n和给出的字符串中不同字符的个数nc,统计这个字符串一共有多少不同的长度为n的子串. 思路 ...
- 一步一步学Vue(七)
前言:我以后在文章最后再也不说我下篇博文要写什么,之前说的大家也可以忽略,如果你不忽略,会失望的
- 计算机网络之应用层_part -1
应用层协议原理 一.网络应用程序体系结构 网络应用程序体系结构是由程序研发者设计的,规定了如何在各种端系统中组织该应用程序,主要流行的有两种: 1.客户--服务器体系结构: 有一个总是打开的主机(称为 ...
- 【原创】07. ajax请求,解决sendRedirect 无效
介绍: 后台基于旧代码用的Filter验证,若 Session过期,则跳转登陆页面 前台框架:EasyUI 问题: 最初后台验证不通过: 1 httpServletResponse.sendRedir ...
- Python爬虫初学(二)—— 爬百度贴吧
Python爬虫初学(二)-- 爬百度贴吧 昨天初步接触了爬虫,实现了爬取网络段子并逐条阅读等功能,详见Python爬虫初学(一). 今天准备对百度贴吧下手了,嘿嘿.依然是跟着这个博客学习的,这次仿照 ...
- 27. leetcode 401. Binary Watch
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom ...
- Hibernate批量操作(一)
在项目的开发过程之中,我们常会遇到数据的批量处理问题.在持久层采用Hibernate框架时,在进行批量操作时,需要考虑Hibernate实现机制带来的一些问题. 我们知道在每个Hibernate Se ...
- React Native 系列(六) -- PropTypes
前言 本系列是基于React Native版本号0.44.3写的.在我们之前的通过props实现组件间传值的时候,大家有没有发现在父组件传递值过去,在子控件获取props的时候没有提示,那么如何能实现 ...
- 最短路和次短路问题,dijkstra算法
/* *题目大意: *在一个有向图中,求从s到t两个点之间的最短路和比最短路长1的次短路的条数之和; * *算法思想: *用A*求第K短路,目测会超时,直接在dijkstra算法上求次短路; ...
- ajax执行顺序问题
在一个函数里,执行顺序是先传所有的值到指定url,然后再返回所有的success 解决方法:将ajax改成异步 aysnc:false