using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication1
{
public partial class gridview_lianxi : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
private void Bind()
{
string strsql = ConfigurationManager.ConnectionStrings["str"].ConnectionString;
using (SqlConnection sqlcnn = new SqlConnection(strsql))
{
using (SqlCommand sqlcmm = sqlcnn.CreateCommand())
{
sqlcmm.CommandText = "select ARTICLEID,CLASSID,TITLE,substring([CONTENT],0,20) as con,CLICKCOUNT,PUBLISHER from ArticleInfo";
SqlDataAdapter sd = new SqlDataAdapter(sqlcmm);
DataTable dt = new DataTable();
sd.Fill(dt);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}
}
//用来显示其他页的数据
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
Bind();
}
private double sum = 0;//用来计算总点击量
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//鼠标悬停改变当前行背景色
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");
}
//计算每页的总点击量
if (e.Row.RowIndex >= 0)
{
sum += Convert.ToDouble(e.Row.Cells[5].Text);
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[4].Text = "当前页的总点击量为:";
e.Row.Cells[5].Text = sum.ToString();
}
}
//删除,可删除多行
protected void btn_del_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in this.GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ckb = row.Cells[0].FindControl("CheckBox1") as CheckBox;
if (ckb.Checked)
{
// Response.Write(row.Cells[1].Text);
string str = ConfigurationManager.ConnectionStrings["str"].ConnectionString;
using (SqlConnection sqlCnn = new SqlConnection(str))
{
using (SqlCommand sqlcmm = sqlCnn.CreateCommand())
{
sqlcmm.CommandText = "delete ArticleInfo where ARTICLEID=@id";
sqlcmm.Parameters.AddWithValue("@id", row.Cells[1].Text);
sqlCnn.Open();
int a= sqlcmm.ExecuteNonQuery();
if (a > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('删除成功')</script>");
}
sqlCnn.Close();
this.Bind();
}
}
}
}
}
}
//全选
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
CheckBox ckb = sender as CheckBox;
foreach (GridViewRow row in this.GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
(row.Cells[0].FindControl("CheckBox1") as CheckBox).Checked = ckb.Checked;
}
}
}
}
}
gridview 中实现的一些常见的功能
最新推荐文章于 2023-08-09 09:18:52 发布