前台:
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeBehind="WebForm1.aspx.cs"
Inherits="WebApplication1.WebForm1" %>
<!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>
<style type="text/css">
#mydiv
{
position: absolute;
width: 600px;
height: 500px;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -300px;
display: none;
background-color: Gray;
}
#divcover
{
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: Black;
opacity: 0.3;
display: none;
}
</style>
<script type="text/javascript">
function showinfo() {
if (confirm('真的要删除吗') == false)
return false;
}
function showdiv() {
document.getElementById('divcover').style.display = 'block';
document.getElementById('mydiv').style.display = 'block';
}
function closediv() {
document.getElementById('divcover').style.display = 'none';
document.getElementById('mydiv').style.display = 'none';
}
</script>
<link rel="stylesheet" href="Kindeditor/themes/default/default.css" />
<link rel="stylesheet" href="Kindeditor/plugins/code/prettify.css" />
<script charset="utf-8" src="Kindeditor/kindeditor.js"></script>
<script charset="utf-8" src="Kindeditor/lang/zh_CN.js"></script>
<script charset="utf-8" src="Kindeditor/plugins/code/prettify.js"></script>
<script>
KindEditor.ready(function (K) {
var editor1 = K.create('#content1', {
cssPath: 'Kindeditor/plugins/code/prettify.css',
uploadJson: 'Kindeditor/asp.net/upload_json.ashx',
fileManagerJson: 'Kindeditor/asp.net/file_manager_json.ashx',
allowFileManager: true,
afterCreate: function () {
var self = this;
K.ctrl(document, 13, function () {
self.sync();
K('form[name=example]')[0].submit();
});
K.ctrl(self.edit.doc, 13, function () {
self.sync();
K('form[name=example]')[0].submit();
});
}
});
prettyPrint();
});
</script>
</head>
<body>
<asp:Label ID="Label1" runat="server" Visible="false" Text=""></asp:Label>
<form id="example" runat="server">
<div id="divcover">
</div>
<%--弹出层--%>
<div id="mydiv">
<div id="divclose">
<a href="javascript:closediv();">关闭窗口</a></div>
<table>
<tr>
<td>
标题
</td>
<td>
<asp:TextBox ID="txtTitle" runat="server" Width="250px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
内容
</td>
<td>
<textarea id="content1" cols="100" rows="8" style="width: 550px; height: 360px; visibility: hidden;"
runat="server"></textarea>
</td>
</tr>
<tr>
<td>
类别
</td>
<td>
<asp:DropDownList ID="ddlClassName" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
用户
</td>
<td>
<asp:DropDownList ID="ddlUser" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:Button ID="btnUpdate" runat="server" Text="保存" OnClick="btnUpdate_Click" />
</td>
</tr>
</table>
</div>
<div>
<table>
<tr>
<td>
<asp:LinkButton ID="btnAdd" runat="server" OnClick="btnAdd_Click">添加</asp:LinkButton>
<asp:Button ID="btnDelete" runat="server" Text="删除" OnClientClick="return showinfo()"
OnClick="btnDelete_Click1" />
<input id="Button1" type="button" value="添加-弹出层" onclick="showdiv();" />
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting="True"
OnRowDataBound="GridView1_RowDataBound" OnSorting="GridView1_Sorting" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="选择">
<ItemTemplate>
<asp:CheckBox ID="ck1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="标题">
<ItemTemplate>
<a href='WebShowXx.aspx?id=<%# Eval("Id") %>'>
<%# Eval("NewsTitle") %></a>
</ItemTemplate>
<HeaderStyle Width="200px" />
<ItemStyle Width="200px" />
</asp:TemplateField>
<asp:BoundField DataField="NewsContent" HeaderText="内容" />
<asp:BoundField DataField="RealName" HeaderText="创建者" SortExpression="RealName" />
<asp:BoundField DataField="CreateTime" DataFormatString="{0:yyyy-MM-dd hh:mm:ss}"
HeaderText="创建时间" SortExpression="CreateTime" />
<asp:BoundField DataField="ClassName" HeaderText="类别" />
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="images/edit.jpg" AlternateText="编辑" CommandArgument='<%#Eval("Id") %>'
OnClick="btnEdit_Click" />
</ItemTemplate>
<HeaderStyle Width="30px" />
<ItemStyle Width="30px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="操作">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" CommandArgument='<%#Eval("Id") %>' AlternateText="删除" ImageUrl="images/delete.jpg" runat="server"
OnClick="btnDelete_Click" OnClientClick="return showinfo();"/>
</ItemTemplate>
<HeaderStyle Width="30px" />
<ItemStyle Width="30px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="btnFirst" runat="server" OnClick="btnFirst_Click">第一页 </asp:LinkButton>
<asp:LinkButton ID="btnPre" runat="server" OnClick="btnPre_Click">上一页</asp:LinkButton>
<asp:LinkButton ID="btnNext" runat="server" OnClick="btnNext_Click">下一页</asp:LinkButton>
<asp:LinkButton ID="btnLast" runat="server" OnClick="btnLast_Click">最后一页</asp:LinkButton>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
int pagesize = 20;
int lcount = 0;
int xcount = 0;
//Dictionary<string, string> dic = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
//Label1.Text = content1.InnerHtml;
Label1.Text = Request.Form["content1"];
if (IsPostBack==false)
{
//当Request.QueryString["pageindex"]不为空的时候,表示是从编辑页面跳转回来的,为空则表明是本页面首次加载。首次加载则设置页码为1,若是从编辑页面跳转回来,则设置页码为跳转前本页的页码
if (!string.IsNullOrEmpty(Request.QueryString["pageindex"]))
{
ViewState["pageindex"] = Request.QueryString["pageindex"];
}
else
{
ViewState["pageindex"] = 1;
}
GetCount();
LoadData();
LoadUser();
LoadClass();
}
}
private void LoadUser()
{
DataTable dt= SqlHelper.ExecuteDataTable("SELECT * FROM T_User", null);
this.ddlUser.DataSource = dt;
this.ddlUser.DataTextField = "RealName";
this.ddlUser.DataValueField = "UserId";
this.ddlUser.DataBind();
}
//绑定类别
private void LoadClass()
{
DataTable dt = SqlHelper.ExecuteDataTable("SELECT * FROM T_NewsClass", null);
this.ddlClassName.DataSource = dt;
this.ddlClassName.DataTextField = "ClassName";
this.ddlClassName.DataValueField = "ClassId";
this.ddlClassName.DataBind();
}
private void GetCount()
{
int totalcount=Convert.ToInt32(SqlHelper.ExeceteScalar(" SELECT COUNT(*) FROM T_News1", null));
if (totalcount % pagesize == 0)
{
ViewState["pagelastindex"] = totalcount / pagesize;
}
else
{
ViewState["pagelastindex"] = totalcount / pagesize + 1;
}
}
private void LoadData()
{
string sqlstr = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY T1.Id DESC)AS rownumber, T1.Id,T1.NewsTitle,SUBSTRING(T1.NewsContent,0,20)+'......' AS NewsContent,T1.CreateTime,T2.ClassName,T3.RealName FROM T_News1 T1 INNER JOIN T_NewsClass T2 ON T1.ClassId=T2.ClassId INNER JOIN T_User T3 ON T1.NewsCreator=T3.UserId)A WHERE A.rownumber>(@pageindex-1)*@pagesize AND A.rownumber<=@pageindex*@pagesize";
if (ViewState["sortexp"]!=null)
{
Dictionary<string, string> dic = ViewState["sortexp"] as Dictionary<string, string>;
string sqlorder = string.Empty;
foreach (KeyValuePair<string,string> item in dic)
{
sqlorder += item.Key + " " + item.Value+",";
}
sqlstr=sqlstr+" ORDER BY "+sqlorder.TrimEnd(',');
}
SqlParameter parampageindex = new SqlParameter("@pageindex", ViewState["pageindex"]);
SqlParameter parampagesize = new SqlParameter("@pagesize", pagesize);
SqlParameter[] param = new SqlParameter[2]{parampageindex,parampagesize};
DataTable dt = SqlHelper.ExecuteDataTable(sqlstr, param);
//将查询出来的数据绑定到GridView
//原来需要手动拼接字符串的工作由GridView代劳了
this.GridView1.DataSource = dt;
//DataBind负责拼接字符串
this.GridView1.DataBind();
}
protected void btnFirst_Click(object sender, EventArgs e)
{
ViewState["pageindex"] = 1;
LoadData();
}
protected void btnPre_Click(object sender, EventArgs e)
{
int pageindex = Convert.ToInt32(ViewState["pageindex"]);
if (pageindex > 1)
{
pageindex--;
ViewState["pageindex"] = pageindex;
LoadData();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
int pageindex = Convert.ToInt32(ViewState["pageindex"]);
if (pageindex<Convert.ToInt32(ViewState["pagelastindex"]))
{
pageindex++;
ViewState["pageindex"] = pageindex;
LoadData();
}
}
protected void btnLast_Click(object sender, EventArgs e)
{
ViewState["pageindex"] = ViewState["pagelastindex"];
LoadData();
}
protected void btnEdit_Click(object sender, EventArgs e)
{
LinkButton btnEdit = sender as LinkButton;
Response.Redirect("WebEdit2.aspx?pageindex=" +Convert.ToInt32(ViewState["pageindex"]) + "&id=" + btnEdit.CommandArgument);
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//sender 表示触发此事件的对象,在这里就是Id为btnDelete的LinkButton对象,但是默认此对象为object类型,object类型没有CommandArgument属性,此属性为LinkButton类型对象所有,所以我们需要自己动手将其转换为LinkButton类型,才可以获取CommandArgument属性存储的值
ImageButton btnDelete = sender as ImageButton;
SqlParameter[] param = new SqlParameter[1]{
new SqlParameter("@id",btnDelete.CommandArgument)
};
if (SqlHelper.ExecuteNoneQuery("DELETE FROM T_News1 WHERE Id=@id", param) == true)
{
LoadData();
}
}
//添加
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("WebAdd.aspx");
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//判断用户点击了哪个排序字段
//说明用户第一次点击排序字段
if (ViewState["sortexp"] == null)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add(e.SortExpression, "ASC");
ViewState["sortexp"] = dic;
}
else//用户第二次或者第N次点击排序字段
{
Dictionary<string, string> dic = ViewState["sortexp"] as Dictionary<string, string>;
//判断用户本次点击的排序字段是否和上次点击的排序字段一致,如果一致的话,那么就更改此字段的排序规则,如果不是就清除上次的排序字段,添加新的排序字段和规则(这是根据一个字段排序的情况)
if (dic.ContainsKey(e.SortExpression))
{
//如果上次是升序,则改为降序,如果是降序则改为升序
if (dic[e.SortExpression] == "ASC")
{
dic[e.SortExpression] = "DESC";
}
else
{
dic[e.SortExpression] = "ASC";
}
//ViewState["sortexp"] = dic;
}
else//清除上次排序字段和规则,添加新的排序字段和规则
{
//dic.Clear();
dic.Add(e.SortExpression, "ASC");
//ViewState["sortexp"] = dic;
}
}
//重新加载数据
LoadData();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
#region 添加排序指示符
//RowDataBound事件的特殊之处在于,每加载一行都会执行一遍
//判断当前加载的是哪种类型的行,我们的目的是在标题行上做更改
if (e.Row.RowType == DataControlRowType.Header)
{
//遍历标题行中的所有列,找出包含控件的列。因为我们知道拍序列已经成为LinkButton控件了。
for (int i = 0; i < e.Row.Cells.Count; i++)
{
//在目前的程序中,只有拍序列里包含控件,其他列只是文字而已
if (e.Row.Cells[i].Controls.Count > 0)
{
LinkButton link = e.Row.Cells[i].Controls[0] as LinkButton;
//经过调试发现LiknButton的CommandArgument属性存储的就是当前排序列的字段名称
string sortexp = link.CommandArgument;
if (ViewState["sortexp"] != null)
{
Dictionary<string, string> dic = ViewState["sortexp"] as Dictionary<string, string>;
if (dic.ContainsKey(sortexp))
{
Literal li = new Literal();
//在viewstate中查询用户点当前点击的排序字段对应的排序规则,根据降序和升序动态的添加指示箭头
if (dic[sortexp] == "ASC")
{
li.Text = "↑";
}
else
{
li.Text = "↓";
}
//将包含排序指示箭头的控件添加到当前的排序列中
e.Row.Cells[i].Controls.Add(li);
}
}
}
}
}
#endregion
#region 将刘晓飞创建的行的背景色设置为突出显示
//设置背景色
if (e.Row.RowType==DataControlRowType.DataRow)
{
if (e.Row.Cells[3].Text=="刘晓飞")
{
e.Row.BackColor = Color.Aqua;
}
}
#endregion
#region 分别计算出每一页中创建者为刘晓飞和肖维哲的新闻记录的数量
if (e.Row.RowType==DataControlRowType.DataRow)
{
if (e.Row.Cells[3].Text=="刘晓飞")
{
lcount++;
}
else if (e.Row.Cells[3].Text=="肖唯哲")
{
xcount++;
}
}
//将最后结果输出到页脚
if (e.Row.RowType==DataControlRowType.Footer)
{
e.Row.Cells[0].Text = string.Format("刘晓飞:{0},肖伟哲:{1}",lcount,xcount);
//合并单元格,就是删除多余的单元格,然后让剩下的单元格占据所有单元格的宽度之和
e.Row.Cells.RemoveAt(7);
e.Row.Cells.RemoveAt(6);
e.Row.Cells.RemoveAt(5);
e.Row.Cells.RemoveAt(4);
e.Row.Cells.RemoveAt(3);
e.Row.Cells.RemoveAt(2);
e.Row.Cells.RemoveAt(1);
e.Row.Cells[0].ColumnSpan = 8;
e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Right;
}
#endregion
}
protected void btnDelete_Click1(object sender, EventArgs e)
{
//获取选中的行
string sqlid=string.Empty;
foreach (GridViewRow row in this.GridView1.Rows)
{
CheckBox chek=row.Cells[0].FindControl("ck1") as CheckBox;
if (chek.Checked==true)
{
ImageButton link = row.Cells[6].FindControl("btnEdit") as ImageButton;
sqlid += link.CommandArgument + ",";
}
}
if (DeleteNews(sqlid.TrimEnd(','))==true)
{
ClientScript.RegisterStartupScript(this.GetType(), "infomation", "alert('删除成功')", true);
LoadData();
}
}
private bool DeleteNews(string sqlid)
{
return SqlHelper.ExecuteNoneQuery(" DELETE FROM T_News1 WHERE Id IN(" + sqlid + ")", null);
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
#region 获取用户输入和选择的值
string title = txtTitle.Text;
string content = Label1.Text;
string userid = this.ddlUser.SelectedItem.Value;
string classid = this.ddlClassName.SelectedItem.Value;
#endregion
#region 更改数据
SqlParameter[] param = new SqlParameter[]{
new SqlParameter("@title", title),
new SqlParameter("@content", content),
new SqlParameter("@creator", userid),
new SqlParameter("@classid", classid)
};
if (SqlHelper.ExecuteNoneQuery ("INSERT INTO T_News1(NewsTitle,NewsContent,NewsCreator,ClassId,CreateTime) VALUES(@title,@content,@creator,@classid,GETDATE())", param) == true)
{
Response.Redirect("WebForm1.aspx");
}
#endregion
}
}
}