GridView一些实例
来源:互联网 发布:银行卡余额生成软件 编辑:程序博客网 时间:2024/06/06 12:42
前台代码
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView实例一</title>
<link href="CSS/CSS.css" rel="stylesheet" type="text/css" />
<script language="javascript">
function SelectAll(obj)
{
var allInput = document.getElementsByTagName("input");
//alert(allInput.length);
var loopTime = allInput.length;
for(i = 0;i < loopTime;i++)
{
//alert(allInput[i].type);
if(allInput[i].type == "checkbox")
{
allInput[i].checked = obj.checked;
}
}
}
function GetConfirm(sForm)
{
var flag = false;
var allInput = document.getElementsByTagName("input");
//alert(allInput.length);
var loopTime = allInput.length;
for(i = 0;i < loopTime;i++)
{
//alert(allInput[i].type);
if(allInput[i].type == "checkbox"&& allInput[i].checked == true)
{
flag = true;
}
}
if (!flag)
{
alert("请选择操作纪录!");
return false;
}
else
{
if (window.confirm("确实要删除所选项吗?"))
return true;
else
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 100%; height: 100px; text-align:center;">
<asp:GridView ID="GV_kh" runat="server" Width="100%" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCancelingEdit="GV_kh_RowCancelingEdit" OnRowEditing="GV_kh_RowEditing" OnRowUpdating="GV_kh_RowUpdating" OnRowDeleting="GV_kh_RowDeleting" OnSorting="GV_kh_Sorting" AllowPaging="True" AllowSorting="True" PageSize="5" OnPageIndexChanging="GV_kh_PageIndexChanging" OnDataBound="GV_kh_DataBound" OnRowDataBound="GV_kh_RowDataBound">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="选择">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="编号" SortExpression="id" ReadOnly="True" />
<asp:BoundField DataField="mingcheng" HeaderText="名称" SortExpression="mingcheng" />
<asp:BoundField DataField="dianhua" HeaderText="电话" SortExpression="dianhua" />
<asp:BoundField DataField="dizhi" HeaderText="地址" SortExpression="dizhi" />
<asp:BoundField DataField="youbian" HeaderText="邮编" SortExpression="youbian" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:HyperLinkField
HeaderText="修改" Text="修改" DataNavigateUrlFields="id"
DataNavigateUrlFormatString="play.aspx?id={0}" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
<asp:TemplateField HeaderText="删除" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="del" runat="server" Text="删除" CausesValidation="False" CommandName="Delete" OnClientClick="return confirm('确认要删除吗?')"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<PagerTemplate>
<table width="100%">
<tr>
<td style="text-align:right;text-decoration: none">
第<asp:Label id="lblPageIndex" runat="server" text='<%# ((GridView)Container.Parent.Parent).PageIndex + 1 %>' />页
共<asp:Label id="lblPageCount" runat="server" text='<%# ((GridView)Container.Parent.Parent).PageCount %>' />页
<asp:linkbutton id="btnFirst" runat="server" causesvalidation="False" commandargument="First" commandname="Page" text="首页" style="color: #ffffff; text-decoration:none;" />
<asp:linkbutton id="btnPrev" runat="server" causesvalidation="False" commandargument="Prev" commandname="Page" text="上一页" style="color: #ffffff; text-decoration:none;" />
<asp:linkbutton id="btnNext" runat="server" causesvalidation="False" commandargument="Next" commandname="Page" text="下一页" style="color: #ffffff; text-decoration:none;" />
<asp:linkbutton id="btnLast" runat="server" causesvalidation="False" commandargument="Last" commandname="Page" text="尾页" style="color: #ffffff; text-decoration:none;" />
<asp:textbox id="txtNewPageIndex" runat="server" width="20px" text='<%# ((GridView)Container.Parent.Parent).PageIndex + 1 %>' />
<asp:linkbutton id="btnGo" runat="server" causesvalidation="False" commandargument="-1" commandname="Page" text="GO" style="color: #ffffff; text-decoration:none;"/><!-- here set the CommandArgument of the Go Button to '-1' as the flag -->
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>
<asp:CheckBox ID="allbox" runat="server" Text="全选" />
<asp:Button ID="Button1" runat="server" Text="删 除" OnClick="Button1_Click1" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text=" 添 加" />
</div>
</form>
</body>
</html>
后台代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text.RegularExpressions; //正则表达式
public partial class GridView : System.Web.UI.Page
{
private void GridViewBind(string sql)
{
DbConnection dc = new DbConnection();
SqlConnection mycon = new SqlConnection(dc.ConnectionString);
SqlDataAdapter mypter = new SqlDataAdapter(sql, mycon);
DataSet ds = new DataSet();
mycon.Open();
mypter.Fill(ds,"JB_khxx");
GV_kh.DataSource = ds;
GV_kh.DataBind();
mycon.Close();
}
private void Bind()
{
DbConnection dc = new DbConnection();
string sql = "select * from JB_khxx";
SqlConnection mycon = new SqlConnection(dc.ConnectionString);
SqlDataAdapter mypter = new SqlDataAdapter(sql, mycon);
DataSet ds = new DataSet();
mycon.Open();
mypter.Fill(ds, "JB_khxx");
GV_kh.DataSource = ds;
GV_kh.DataKeyNames = new string[] { "id" };
GV_kh.DataBind();
mycon.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Title = "GridView实例";
Bind();
ViewState["sortDirection"] = "ASC";
allbox.Attributes.Add("onclick", "SelectAll(this)");
Button1.Attributes.Add("onclick", "return GetConfirm(this)");
}
}
protected void GV_kh_RowEditing(object sender, GridViewEditEventArgs e)
{//编辑
GV_kh.EditIndex = e.NewEditIndex;
Bind();
}
protected void GV_kh_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{//取消
GV_kh.EditIndex = -1;
Bind();
}
protected void GV_kh_RowUpdating(object sender, GridViewUpdateEventArgs e)
{//更新
string id = GV_kh.DataKeys[e.RowIndex].Value.ToString();
string mingcheng = ((TextBox)(GV_kh.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();
string dianhua = ((TextBox)(GV_kh.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim();
string dizhi = ((TextBox)(GV_kh.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim();
string youbian = ((TextBox)(GV_kh.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim();
if ((Regex.IsMatch(dianhua, @"^(/(/d{3}/)|/d{3}-)?/d{8}")) && (Regex.IsMatch(youbian, @"^/d{6}")))
{
string sql = "update JB_khxx set mingcheng=@mingcheng,dianhua=@dianhua,dizhi=@dizhi,youbian=@youbian where id=@id";
//string sql = "update JB_khxx set mingcheng='" + mingcheng + "',dianhua='" + dianhua + "',dizhi='" + dizhi + "',youbian='" + youbian + "' where id='" + id + "'";
DbConnection dc = new DbConnection();
SqlConnection mycon = new SqlConnection(dc.ConnectionString);
SqlCommand mycom = new SqlCommand(sql, mycon);
mycom.Parameters.Add("@id", System.Data.SqlDbType.VarChar);
mycom.Parameters.Add("@mingcheng", System.Data.SqlDbType.VarChar);
mycom.Parameters.Add("@dianhua", System.Data.SqlDbType.VarChar);
mycom.Parameters.Add("@dizhi", System.Data.SqlDbType.VarChar);
mycom.Parameters.Add("@youbian", System.Data.SqlDbType.VarChar);
mycom.Parameters["@id"].Value = id;
mycom.Parameters["@mingcheng"].Value = mingcheng;
mycom.Parameters["@dianhua"].Value = dianhua;
mycom.Parameters["@dizhi"].Value = dizhi;
mycom.Parameters["@youbian"].Value = youbian;
mycon.Open();
mycom.ExecuteNonQuery();
mycon.Close();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('电话号码或邮编错误!')</script>");
//Response.Write("<script language='JavaScript'>window.alert('电话号码或邮编错误!')</script>");//使用后改变了字体大小
//this.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('操作成功');window.location.href='other.aspx'", true);成功转到other.aspx页面
}
GV_kh.EditIndex = -1;
Bind();
}
protected void GV_kh_RowDeleting(object sender, GridViewDeleteEventArgs e)
{//删除
string id = GV_kh.DataKeys[e.RowIndex].Value.ToString();
string sql = "delete from JB_khxx where id = @id";
DbConnection dc = new DbConnection();
SqlConnection mycon = new SqlConnection(dc.ConnectionString);
SqlCommand mycom = new SqlCommand(sql, mycon);
mycom.Parameters.Add("@id", System.Data.SqlDbType.VarChar).Value = id;
mycon.Open();
mycom.ExecuteNonQuery();
mycon.Close();
Bind();
}
protected void GV_kh_Sorting(object sender, GridViewSortEventArgs e)
{
//排序
GV_kh.EditIndex = -1;
if (ViewState["sortColumn"] == null)
{
ViewState["sortColumn"] = e.SortExpression.ToString();
ViewState["sortDirection"] = "ASC";
}
else
{
if (ViewState["sortDirection"].ToString() == "DESC")
{
ViewState["sortDirection"] = "ASC";
}
else
{
ViewState["sortDirection"] = "DESC";
}
}
string strSql = "SELECT * FROM JB_khxx";
strSql = strSql + " order by " + e.SortExpression + " " + ViewState["sortDirection"];
GridViewBind(strSql);
}
protected void GV_kh_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView theGrid = sender as GridView; // refer to the GridView
int newPageIndex = 0;
if (-2 == e.NewPageIndex)
{ // when click the "GO" Button
TextBox txtNewPageIndex = null;
//GridViewRow pagerRow = theGrid.Controls[0].Controls[theGrid.Controls[0].Controls.Count - 1] as GridViewRow; // refer to PagerTemplate
GridViewRow pagerRow = GV_kh.BottomPagerRow; //GridView较DataGrid提供了更多的API,获取分页块可以使用BottomPagerRow 或者TopPagerRow,当然还增加了HeaderRow和FooterRow
//updated at 2006年6月21日3:15:33
if (null != pagerRow)
{
txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox; // refer to the TextBox with the NewPageIndex value
}
if (null != txtNewPageIndex)
{
newPageIndex = int.Parse(txtNewPageIndex.Text) - 1; // get the NewPageIndex
}
}
else
{ // when click the first, last, previous and next Button
newPageIndex = e.NewPageIndex;
}
// check to prevent form the NewPageIndex out of the range
newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
newPageIndex = newPageIndex >= GV_kh.PageCount ? GV_kh.PageCount - 1 : newPageIndex;
// specify the NewPageIndex
GV_kh.PageIndex = newPageIndex;
Bind();//数据绑定
// rebind the control
// in this case of retrieving the data using the xxxDataSoucr control,
// just do nothing, because the asp.net engine binds the data automatically
}
protected void GV_kh_DataBound(object sender, EventArgs e)
{
}
protected void GV_kh_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[8].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除吗?')");
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c;");
}
//方法 一
//int i;
////执行循环,保证每条数据都可以更新
//for (i = 0; i < GridView1.Rows.Count; i++)
//{
// //首先判断是否是数据行
// if (e.Row.RowType == DataControlRowType.DataRow)
// {
// //当鼠标停留时更改背景色
// e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");
// //当鼠标移开时还原背景色
// e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
// }
//}
}
protected void delall_Click(object sender, EventArgs e)
{//全部删除
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string sql = "delete from JB_khxx where '1' = '2'";
DbConnection dc = new DbConnection();
SqlConnection mycon = new SqlConnection(dc.ConnectionString);
for (int i = 0; i <= GV_kh.Rows.Count - 1; i++)
{
CheckBox box = (CheckBox)GV_kh.Rows[i].FindControl("CheckBox1");
if (box.Checked == true)
{
sql = "delete from JB_khxx where id='" + GV_kh.DataKeys[i].Value + "'";
}
SqlCommand mycom = new SqlCommand(sql, mycon);
mycon.Open();
mycom.ExecuteNonQuery();
mycon.Close();
}
Bind();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("GridView_add.aspx");
}
}
- GridView一些实例
- GridView 实例
- GridView实例
- GridView实例
- GridView实例
- GridView实例
- gridview 实例
- GridView大全应用实例
- GridView 使用实例
- gridview嵌套实例
- GridView结合SimpleAdapter实例
- GridView嵌套应用实例
- android 组件GridView实例
- GridView使用一些记录
- GridView一些常用
- GridView的一些技巧
- gridview的一些应用
- 一些GridView的扩展
- eclipse+workshop studio (nitrox)使用入门
- C语言 算术表达式
- 反转数
- 职场
- 计算机缩写名
- GridView一些实例
- windows运行的命令集锦
- smartupload -- 批量上传模块
- php header
- 对话框类的设计
- oracle日期函数
- DataList实例
- Datalist嵌套
- ADO数据库错误信息表