GridView控件,DataList控件,Repeater控件是常用的数据绑定控件,而其中GridView(2003版本对应的控件是DataGrid)是三者中最为常用的,下面将通过一个简单的例子把GridView中一些使用方法集中在一起,包括GridView中自带分页的使用,GridView中删除当前行的操作,GridView中更新当前行的操作,GridView中HyperLinkField列的使用.
页面前台代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridView.aspx.cs" Inherits="Demo.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>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ArticleID" OnRowDeleting="GridView1_RowDeleting" AllowPaging="True" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnPageIndexChanging="GridView1_PageIndexChanging" >
<Columns>
<asp:BoundField DataField="articleid" HeaderText="新闻ID" />
<asp:HyperLinkField DataNavigateUrlFields="articleid" DataNavigateUrlFormatString="article.aspx?id={0}"
DataTextField="title" HeaderText="新闻标题" />
<asp:BoundField DataField="intime" HeaderText="发布时间" />
<asp:CheckBoxField DataField="checkup" HeaderText="通过(√)" />
<asp:CommandField EditText="审核" HeaderText="审核" SelectText="审核" ShowSelectButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
cs文件代码如下:
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;
public partial class admin_admin_article : MyPage1
{
protected System.Data.SqlClient.SqlConnection conn; //添加数据库的操作对象
protected System.Data.SqlClient.SqlDataAdapter da;
protected System.Data.DataSet ds;
protected System.Data.SqlClient.SqlCommand comm;
static int i=0;
protected void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
getClass();
getArticle();
}
}
private void getClass()
{
conn = DB.CreateConn();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from db_fClass", conn);//标题内容连接
ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "ClassName");
conn.Close();
}
catch (SqlException e1)
{
myLabel.Text = "数据库操作错误:" + e1.Message;
}
ClassName.DataSource = ds.Tables["ClassName"].DefaultView;
ClassName.DataTextField = "className";
ClassName.DataValueField = "classId";
ClassName.DataBind();
conn.Close();
}
private void getArticle() //取得Article数据
{
conn = DB.CreateConn();//取连接字符串,建立连接
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("SELECT * FROM db_Article where classId=" + this.ClassName.SelectedValue + " ORDER BY topnew DESC,intime DESC", conn);
ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "Article");
conn.Close();
}
catch (SqlException e1)
{
myLabel.Text = "数据库操作错误:" + e1.Message;
}
MyDataGrid.DataSource = ds.Tables["Article"].DefaultView;
MyDataGrid.DataBind();
lblCurrentIndex.Text = "第" + ((Int32)MyDataGrid.CurrentPageIndex + 1) + "页";
lblPageCount.Text = "/共" + MyDataGrid.PageCount + "页";
}
public void PagerButtonClick(Object sender, EventArgs e)
{
//获得LinkButton的参数值
string arg = ((LinkButton)sender).CommandArgument;
switch(arg)
{
case ("next"):
{
if (MyDataGrid.CurrentPageIndex < (MyDataGrid.PageCount - 1))
MyDataGrid.CurrentPageIndex ++;
break;
}
case ("prev"):
{
if (MyDataGrid.CurrentPageIndex > 0)
MyDataGrid.CurrentPageIndex --;
break;
}
case ("last"):
{
MyDataGrid.CurrentPageIndex = (MyDataGrid.PageCount - 1);//currentpageinedxcurrentpageindexcurrentpagendexcurrentpageindexcurrentpageindex
break;
}
case("first"):
{
MyDataGrid.CurrentPageIndex =0;
break;
}
}
if (i == 0)
{
getArticle();
}
else
{
SearchArticle();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
}
#endregion
protected void LinkButton1_Click(object sender, System.EventArgs e) //搜索数据库
{
MyDataGrid.CurrentPageIndex=0;
SearchArticle();
}
private void SearchArticle()
{
if (i == 0)
{
this.MyDataGrid.CurrentPageIndex = 0;
}
conn = DB.CreateConn();//取连接字符串,建连接
da = new SqlDataAdapter();
if (search.SelectedIndex == 0)
{
da.SelectCommand = new SqlCommand("sp_searchArticleByTitle", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@title", SqlDbType.NVarChar, 500);
da.SelectCommand.Parameters["@title"].Value = keyword.Text.Trim();
}
else
{
da.SelectCommand = new SqlCommand("sp_searchArticleByContent", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("@content", SqlDbType.NText);
da.SelectCommand.Parameters["@content"].Value = keyword.Text.Trim();
}
ds = new DataSet();
try
{
da.Fill(ds, "Invite");
}
catch (SqlException e1)
{
myLabel.Text = "数据库操作错误:" + e1.Message;
}
i++;
MyDataGrid.DataSource = ds;
MyDataGrid.DataBind();
lblCurrentIndex.Text = "第" + ((Int32)MyDataGrid.CurrentPageIndex + 1) + "页";
lblPageCount.Text = "/共" + MyDataGrid.PageCount + "页";
}
protected void ClassName_SelectedIndexChanged(object sender, System.EventArgs e)
{
MyDataGrid.CurrentPageIndex = 0;//设置页码为0
getData();
}
protected void subClass_SelectedIndexChanged(object sender, System.EventArgs e)
{
MyDataGrid.CurrentPageIndex = 0;//设置页码为0
getData();
}
private void getData()
{
conn = DB.CreateConn();
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from db_Article where classId=" + this.ClassName.SelectedValue + "ORDER BY topnew DESC,intime desc", conn);
DataSet ds = new DataSet();
try
{
conn.Open();
da.Fill(ds, "ArtAll");
conn.Close();
}
catch (SqlException e1)
{
myLabel.Text = "数据库操作错误:";
}
MyDataGrid.DataSource = ds.Tables["ArtAll"];
MyDataGrid.DataBind();
lblCurrentIndex.Text = "第" + ((Int32)MyDataGrid.CurrentPageIndex + 1) + "页";
lblPageCount.Text = "/共" + MyDataGrid.PageCount + "页";
}
protected void MyDataGrid_ItemCommand(object source, DataGridCommandEventArgs e)
{
conn = DB.CreateConn();
comm = new SqlCommand("sp_checkUpArticle", conn);
comm.Parameters.Add("@Aid", SqlDbType.BigInt).Value = MyDataGrid.DataKeys[e.Item.ItemIndex];
comm.CommandType = CommandType.StoredProcedure;
try {
conn.Open();
comm.ExecuteNonQuery();
}
catch (Exception ex) { throw ex; }
finally {
conn.Close();
}
i = 0;
getArticle();
}
protected void MyDataGrid_DeleteCommand1(object source, DataGridCommandEventArgs e)删除新闻
{
//string msg = "你确定要删除吗?";
//string ControlName = "OK";
//Page.RegisterStartupScript("onclick", "<script language=/"javascript/">/n if (confirm(/"" + msg + "/"))/n " + ControlName + ".click();/n </script>");
conn = DB.CreateConn();
//comm = new SqlCommand("delete db_Article where articleid=" + MyDataGrid.DataKeys[e.Item.ItemIndex], conn);
comm = new SqlCommand("delete db_Article where articleid=" + MyDataGrid.DataKeys[e.Item.ItemIndex], conn);
try
{
conn.Open();
//int r = comm.ExecuteNonQuery();
//int r = comm.ExecuteNonQuery();
int r = comm.ExecuteNonQuery();
if (r > 0)
{
myLabel.Text = "删除成功!";
}
else
{
myLabel.Text = "删除错误!";
}
}
catch (SqlException e1)
{
myLabel.Text = "数据库操作错误:" + e1.Message;
}
conn.Close();
i = 0;
getArticle();
}
protected void MyDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
((LinkButton)(e.Item.Cells[7].Controls[0])).Attributes.Add("onclick", "return confirm('你确定删除?');");
}
}
protected void MyDataGrid_PageIndexChanged1(object source, DataGridPageChangedEventArgs e)
{
MyDataGrid.CurrentPageIndex = e.NewPageIndex;
if (i == 0)
{
getArticle();
}
else
{
SearchArticle();
}
}
}
上面用到的存储过程脚本:
CREATE proc sp_checkUpArticle
@Aid int
as
declare @checkup bit
select @checkup=checkup from dbo.db_Article where articleid=@Aid
if (@checkup>0)
update dbo.db_Article
set checkup=0
where articleid=@Aid
else
update dbo.db_Article
set checkup=1,
intime=getDate()
where articleid=@Aid
GO
以下是效果图: