网站后台管理之数据列表绑定、删除和修改

更新时间:2023-08-14 15:46:01 阅读量: 人文社科 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

第四章 网站后台管理之数据列表绑定、删除和修改 

1、在本章节中主要学习如何把数据库中的数据绑定显示在页面上,或者对选择的数据进行删除和修改等一系列操作,具体步骤和内容如下所示,效果图如下:

2、新建名称为ArticleList.apsx的母版内容页,点击设计,进入到设计页面。 3、在中数据绑定控件比较多包括: Reapter、DataList、ListView、GridView、DatailsView、FormView等,具体各种数据绑定控件的区别可以上网去了解,在开发过程中用的比较多的为Reapter、DataList、ListView和GridView,而且在前台绑定一般使用Reapter、DataList、ListView,后台绑定数据一般使用GridView,所以我们在可以通过我们最基本的功能来判断使用哪种数据绑定控件,上述数据绑定控件后台的绑定方法差不多,不同的就是前台代码布局,具体如下: (1)、Reapter的前台布局代码如下:

<asp:Repeater ID="Repeater1" runat="server"> <HeaderTemplate>

<table border="0" cellpadding="0" cellspacing="0"> <tr>

<td style="width:150px; border:solid 1px gray;">标题</td> </tr> </table> </HeaderTemplate> <ItemTemplate>

<table border="0" cellpadding="0" cellspacing="0"> <tr>

<td style="width:150px;border:solid 1px gray;"> <asp:Label ID="Label1" runat="server" Text='<%#

Eval("articleTitle") %>'></asp:Label> </td> </tr> </table> </ItemTemplate> </asp:Repeater>

(2)、DataList的前台布局代码如下:

(3)、ListView的前台布局代码如下:

<asp:ListView ID="ListView2" runat="server"> <LayoutTemplate>

<li runat="server" id="itemPlaceholder"></li> </LayoutTemplate> <ItemTemplate>

<li><a href="" target="main"><%# Eval("TypeName") %></a></li> </ItemTemplate> </asp:ListView>

和Reapter的差不多,不重复写。

(4)、GridView的前台布局代码如下:

在下面的操作中我们主要以GridView控件的操作为主作为演示:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> <Columns>

<asp:TemplateField HeaderText="选择"> <ItemTemplate>

<asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="文章标题"> <ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Eval("articleTitle") %>'></asp:Label> </ItemTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="文章类型"> <ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%#

Eval("articleTypeId") %>'></asp:Label> </ItemTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="发布时间"> <ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Eval("articleTime") %>'></asp:Label> </ItemTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="文章状态"> <ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Eval("articleState") %>'></asp:Label> </ItemTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="操作"> <ItemTemplate>

<asp:LinkButton ID="LinkButton1" runat="server">删除</asp:LinkButton> </ItemTemplate> </asp:TemplateField>

</Columns> </asp:GridView>

效果图如下

(5)、后台代码如下:

protected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) {

BindGridView(); } }

public void BindGridView() {

BLL.Article articleBll = new BLL.Article(); DataSet ds = new DataSet();

ds = articleBll.GetList(""); GridView1.DataSource = ds;

GridView1.DataBind(); }

运行效果如如下:

4、如果数据太多,可以通过数据关键字来查询和过滤,此时需要在前台添加文本框控件让用户输入查询条件,效果如下:

5、双击搜索按钮,进入后台点击事件,因为需要把输入的关键字作为数据库搜索的条件,所以需要在绑定数据源的代码中添加条件,修改代码如下:

public void BindGridView() {

string key = txtKey.Text.Trim();

BLL.Article articleBll = new BLL.Article(); DataSet ds = new DataSet();

ds = articleBll.GetList(" articleTitle like '%'"+key+"'%'");

6、在按钮单击事件中添加如下代码:

protected void btnSearch_Click(object sender, EventArgs e) {

BindGridView(); }

7、重新生成解决方案,查看运行效果如下:

8、当数据太多时,我们需要给列表添加分页,可以让我们更好的查看列表数据,所以我们需要给列表添加分页,实现如下效果:

9、下面就演示如何使用aspnetPager分页控件进行分页,分页包括前台代码和后台代码,开始写代码之前我们需要引用一个外部的dll文件

10、然后在前台写如下代码把需要使用的外部控件在页面中注册,<%@ Register

Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="asp" %>

11、然后写代码对分页控件的样式进行修饰,具体代码如下:

<div style="margin: 10px 0 10px 0; padding-bottom: 10px;">

<webdiyer:AspNetPager Style="font-size: 12px" ID="AspNetPager1" runat="server" CustomInfoClass="formbutton"

SubmitButtonText="GO" SubmitButtonClass="formfield" CssClass="formfield" PrevPageText="前一页"

PageSize="10" NextPageText="下一页" LastPageText="尾页" FirstPageText="首页" ShowInputBox="Always"

CustomInfoTextAlign="Center" ShowNavigationToolTip="True" CustomInfoHTML="第 <font color='red'> <b>%CurrentPageIndex% </b> </font>页 共%PageCount% 页 %StartRecordIndex%-%EndRecordIndex%"

InputBoxStyle="width:19px" meta:resourceKey="AspNetPager1" Width="506px" ShowCustomInfoSection="Left"

OnPageChanged="AspNetPager1_PageChanged" HorizontalAlign="Center" EnableTheming="True"

NumericButtonCount="4" Wrap="False"> </webdiyer:AspNetPager> </div>

如果需要修改每页显示的条数对该参数进行修改PageSize="5"。

12、在后台代码中首先需要编写绑定分页控件的代码,具体如下:

public void BindGridView() {

BLL.Article articleBll = new BLL.Article(); DataSet ds = new DataSet(); ds = articleBll.GetList("");

PagedDataSource pgs = new PagedDataSource(); DataView dv; if (ds == null) {

dv = new DataView(); } else {

dv = ds.Tables[0].DefaultView; }

AspNetPager1.RecordCount = dv.Count; pgs.DataSource = dv; pgs.AllowPaging = true;

pgs.CurrentPageIndex = AspNetPager1.CurrentPageIndex - 1; pgs.PageSize = AspNetPager1.PageSize; GridView1.DataSource = pgs; GridView1.DataBind(); }

protected void AspNetPager1_PageChanged(object sender, EventArgs e) { }

13、绑定数据的代码写好之后,运行结果如下:

14、点击分页控件当中的第2页或者下一页,观看运行结果,发现数据不变化。

15、我们需要在点击事件中重新对数据进行绑定,具体代码如下:

protected void AspNetPager1_PageChanged(object sender, EventArgs e) {

BindGridView(); }

重新生成,查看运行效果如下:

16、仔细一看运行效果,发现文章类型和文章状态显示为数字,不符合我们的要求,我们需要的是文章类型的具体名称和文章状态的具体名称,所以需要绑定后台的方法获取名称,具体代码如下: 后台代码:

/// <summary>

/// 根据类型编号获取类型名称 /// </summary> /// <returns></returns>

public string GetNameByTypeId(int typeId) {

BLL.ArticleType aTypeBll = new BLL.ArticleType(); Model.ArticleType aTypeModel = new Model.ArticleType();

aTypeModel = aTypeBll.GetModel(typeId); return aTypeModel.ArticleTypeName.Trim() ;

}

前台代码修改为:

<asp:TemplateField HeaderText="文章类型"> <ItemTemplate>

<asp:Label ID="Label2" runat="server"

Text='<%# GetNameByTypeId(Convert.ToInt32( Eval("articleTypeId"))) %>'></asp:Label> </ItemTemplate> </asp:TemplateField>

运行效果如下:

17、如果文章的状态只包括两种,我们可以用三元运算符来处理,具体代码如下:

<asp:TemplateField HeaderText="文章状态"> <ItemTemplate>

<asp:Label ID="Label4" runat="server"

Text='<%# Eval("articleState").ToString()=="0"?"未审核":"已审核" %>'></asp:Label>

</ItemTemplate> </asp:TemplateField>

运行效果如下:

18、当文章是已审核的状态时,管理可以取消审核,当文章是未审核状态时,管理员可以审核,所以需要实现这个功能来方便管理员管理文章。

19、首先在GridView控件中,添加Row_DataBound事件,然后添加两个隐藏按钮,一个隐藏域控件,用来判断控件是否显示,具体代码如下: 前台代码:

onrowdatabound="GridView1_RowDataBound

<asp:TemplateField HeaderText="审核操作"> <ItemTemplate>

<asp:HiddenField ID="HiddenField1" Value='<%# Eval("articleState") %>' runat="server" /> <asp:LinkButton ID="lbtnOk" Visible="false" runat="server">审核</asp:LinkButton> <asp:LinkButton ID="lbtnCancel" Visible="false" runat="server">取消审核</asp:LinkButton> </ItemTemplate> </asp:TemplateField>

后台代码:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {

if (e.Row.RowIndex < 0) return;

HiddenField hdId = (HiddenField)e.Row.FindControl("HiddenField1");//获取主键值 LinkButton btnOk = (LinkButton)e.Row.FindControl("lbtnOk");

LinkButton btnCancelOk = (LinkButton)e.Row.FindControl("lbtnCancel"); if (hdId.Value == "0") {

btnOk.Visible = true; } else

if (hdId.Value == "1") {

btnCancelOk.Visible = true; } }

运行效果如下:

20、运行效果中点击取消审核或审核按钮无效,所以需要给这两个按钮添加事件,首先在GridView中添加Row_Command的事件,然后修改两个按钮的属性,再写后台功能代码,具体代码如下: 前台代码:

onrowcommand="GridView1_RowCommand"

<asp:TemplateField HeaderText="审核操作"> <ItemTemplate>

<asp:HiddenField ID="HiddenField1" Value='<%# Eval("articleState") %>' runat="server" />

<asp:LinkButton ID="lbtnOk" Visible="false" CommandArgument='<%# Eval("articleId") %>'

CommandName="Ok" runat="server">审核通过</asp:LinkButton> <asp:LinkButton ID="lbtnCancel" Visible="false" CommandArgument='<%# Eval("articleId") %>'

CommandName="CancelOk" runat="server">取消审核</asp:LinkButton> </ItemTemplate> </asp:TemplateField>

后台代码:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {

BLL.Article aBll = new BLL.Article(); Model.Article aModel = new Model.Article();

aModel = aBll.GetModel(Convert.ToInt32(mandArgument)); switch (mandName) {

case "Ok":

aModel.articleState = 1; aBll.Update(aModel); break; case "CancelOk":

aModel.articleState =0; aBll.Update(aModel); break; }

BindGridView();//记住要重新绑定数据源 }

21、为了避免管理员不小心点击按钮,需要给按钮一个确认提交的事件,在LinkButton中添加OnClientClick属性,具体代码如下:

<asp:LinkButton ID="lbtnOk" OnClientClick="return confirm('确认审核通过?')" Visible="false" CommandArgument='<%# Eval("articleId") %>' CommandName="Ok" runat="server">审核通过</asp:LinkButton>

22、文章的列表页已经绑定好了,如果发现有不需要的文章,需要对其进行删除,如果有很多文章需要删除,不可能会一个一个去点击删除,所以需要批量删除。 接下来在列表中实现单个删除和批量删除文章的功能。

(1) 单个删除:首先添加删除按钮,然后在按钮中添加删除命令和传递参数,

最后在后台代码中添加删除功能,具体代码如下:

<asp:TemplateField HeaderText="操作"> <ItemTemplate>

<asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("articleId") %>' CommandName="DelArticle" runat="server">删除</asp:LinkButton> </ItemTemplate> </asp:TemplateField>

在Row_Command事件中添加代码

case "DelArticle":

bool s =aBll.Delete(Convert.ToInt32(mandArgument)); if (s) {

BindGridView();//记住要重新绑定数据源

Page.RegisterClientScriptBlock("", "<script>alert('删除成功');window.location.href='ArticleList.aspx'</script>");//弹出提示框提示 } else {

Page.RegisterClientScriptBlock("", "<script>alert('删除失败

');window.location.href='ArticleList.aspx'</script>");//弹出提示框提示 } break;

运行效果如下:

(2) 批量删除:首先需要在每行数据中都添加一个复选框CheckBox,然后在

GridView外添加一个全选的复选框进行操作,双击进入全选的复选框的点击事件,编写功能代码,具体代码如下:

<asp:CheckBox ID="CheckBox2" Text="点击全选" runat="server" AutoPostBack="true" oncheckedchanged="CheckBox2_CheckedChanged" />

public void CheckAll() {

for (int i = 0; i < GridView1.Rows.Count; i++) {

CheckBox ck = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); ck.Checked = CheckBox2.Checked; }

}

protected void CheckBox2_CheckedChanged(object sender, EventArgs e) {

CheckAll(); }

选择好了要删除的行后,接下来要进行删除操作,双击删除选择项按钮进入单击事件,进行代码编写,具体代码如下:

<asp:LinkButton ID="LinkButton2" runat="server" onclick="LinkButton2_Click" OnClientClick="return confirm('确认删除选择项?')">删除选择项</asp:LinkButton>

protected void LinkButton2_Click(object sender, EventArgs e) {

BLL.Article articleBll= new BLL.Article(); for (int i = 0; i < GridView1.Rows.Count; i++) {

CheckBox ck = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1"); HiddenField hdId = (HiddenField)GridView1.Rows[i].FindControl("HiddenFieldId");

if (ck.Checked == true) {

articleBll.Delete(Convert.ToInt32(hdId.Value)); } }

BindGridView();

Page.RegisterClientScriptBlock("", "<script>alert('批量删除成功');window.location.href='ArticleList.aspx'</script>");

}

23、修改的方式主要包括两种,一种是直接在列表上进行修改,另一种是跳到其他页面进行修改,两种方式使用的情景不一样,第一种一般用在字段比较少很比较简单的情况下,第二种用在字段比较多和比较复杂的情况。

(1)第一种直接在列表页修改,在GridView添加编辑按钮和编辑模板,具体代码如下:

前台代码:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" onrowdatabound="GridView1_RowDataBound"

onrowcommand="GridView1_RowCommand" onrowediting="GridView1_RowEditing" onrowcancelingedit="GridView1_RowCancelingEdit" onrowupdating="GridView1_RowUpdating"> <Columns>

<asp:TemplateField HeaderText="选择"> <EditItemTemplate>

<asp:HiddenField ID="HiddenFieldId" Value='<%# Eval("articleId") %>' runat="server" />

<asp:CheckBox ID="CheckBox1" runat="server" /> </EditItemTemplate> <ItemTemplate>

<asp:HiddenField ID="HiddenFieldId" Value='<%# Eval("articleId") %>' runat="server" />

<asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="文章标题"> <EditItemTemplate>

<asp:TextBox ID="txtTitle" Text='<%# Eval("articleTitle") %>' runat="server"></asp:TextBox> </EditItemTemplate> <ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Eval("articleTitle") %>'></asp:Label> </ItemTemplate> </asp:TemplateField>

<asp:TemplateField HeaderText="文章类型"> <EditItemTemplate>

<asp:DropDownList ID="ddlType" runat="server"> </asp:DropDownList> </EditItemTemplate> <ItemTemplate>

<asp:Label ID="Label2" runat="server" Text='<%#

GetNameByTypeId(Convert.ToInt32( Eval("articleTypeId"))) %>'></asp:Label> </ItemTemplate> </asp:TemplateField>

<asp:CommandField ShowEditButton="True" /> </Columns> </asp:GridView>

后台代码主要包括初始化数据事件、编辑事件、修改事件和取消事件: //初始化下拉框数据事件

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {

if (e.Row.RowIndex < 0) return;

BLL.ArticleType articleTypeBll = new BLL.ArticleType(); DataSet ds = new DataSet(); ds = articleTypeBll.GetList("");

HiddenField hd = (HiddenField)e.Row.FindControl("HiddenFieldId");//获取主键值 BLL.Article articleBll = new BLL.Article(); Model.Article articleModel = new Model.Article();

articleModel = articleBll.GetModel(Convert.ToInt32(hd.Value)); //行的状态是: 编辑状态 或者 (交替行且是编辑状态) if(e.Row.RowState == DataControlRowState.Edit ||

e.Row.RowState == (DataControlRowState.Alternate | DataControlRowState.Edit)) {

DropDownList ddlType = e.Row.FindControl("ddlType") as DropDownList; if (ddlType != null) {

ddlType.DataValueField = "articleTypeId"; ddlType.DataTextField = "articleTypeName"; ddlType.DataSource = ds; ddlType.DataBind();

ddlType.Items.FindByValue(articleModel.articleTypeId.ToString()).Selected = true; } } }

//编辑事件

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {

GridView1.EditIndex = e.NewEditIndex; BindGridView(); }

//修改事件

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {

GridViewRow myrow = GridView1.Rows[e.RowIndex];

HiddenField hd = (HiddenField)myrow.Cells[0].FindControl("HiddenFieldId");//获取主键值

TextBox txtTitle = (TextBox)myrow.Cells[2].FindControl("txtTitle");//获取标题

DropDownList ddlType = myrow.Cells[3].FindControl("ddlType") as DropDownList;//获取下拉框值

BLL.Article articleBll = new BLL.Article(); Model.Article articleModel = new Model.Article();

articleModel = articleBll.GetModel(Convert.ToInt32(hd.Value)); articleModel.articleTitle = txtTitle.Text.Trim();

articleModel.articleTypeId =Convert.ToInt32( ddlType.SelectedItem.Value); articleBll.Update(articleModel);

GridView1.EditIndex = -1; BindGridView(); }

//取消事件

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {

GridView1.EditIndex = -1; BindGridView(); }

运行效果图如下:

(2)第二种方法是跳转到其他页面进行修改,首先需要新建一个页面

ArticleUpdate.aspx,添加相应的控件,然后在GridView中添加一个链接,具体代码如下:

GridView前台代码:

<asp:TemplateField HeaderText="操作">

<ItemTemplate>

<a href='ArticleUpdate.aspx?id=<%# Eval("articleId") %>'>修改</a>

<asp:LinkButton ID="LinkButton1" OnClientClick="return confirm('确认删除?')" CommandArgument='<%# Eval("articleId") %>'

CommandName="DelArticle" runat="server">删除</asp:LinkButton> </ItemTemplate> </asp:TemplateField>

ArticleUpdate页面前台代码略。 后台代码:

首先要通过Request.QueryString[“id”]来接受发送过来的参数,然后通过主键来获取整条文章的数据绑定到相应控件上,最后再提交新提交的数据,具体代码如下:

BLL.Article articleBll = new BLL.Article();//定义对像

Model.Article articleModel = new Model.Article();//定义对象 public static string Id = "";

protected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) {

if (Request.QueryString["id"] != null) {

Id = Request.QueryString["id"];

articleModel = articleBll.GetModel(Convert.ToInt32(Id)); BindArticleType();//调用方法

DropDownList1.Items.FindByValue(articleModel.articleTypeId.ToString().Trim()).Selected = true ; txtTitle.Text = articleModel.articleTitle;

FCKeditor1.Value = articleModel.articleContent.Trim(); if (articleModel.articleState == 1)//获取复选框选择结果 {

CheckBox1.Checked = true; } else {

CheckBox1.Checked = false ; } } } }

/// <summary> /// 绑定文章类型数据 /// </summary>

public void BindArticleType() {

//定义业务逻辑层中ArticleType类的一个对象

BLL.ArticleType articleTypeBll = new BLL.ArticleType(); DataSet ds = new DataSet();//定义一个数据集对象 //调用类中GetList()的方法 ds = articleTypeBll.GetList("");

DropDownList1.DataSource = ds;//给下拉框赋值数据源 DropDownList1.DataBind();//绑定数据源 }

protected void btnUpdate_Click(object sender, EventArgs e) {

articleModel = articleBll.GetModel(Convert.ToInt32(Id)); articleModel.articleTitle = txtTitle.Text.Trim(); articleModel.articleTime = DateTime.Now;

if (CheckBox1.Checked == true)//获取复选框选择结果 {

articleModel.articleState = 1; } else {

articleModel.articleState = 0; }

articleModel.articleContent = FCKeditor1.Value;

articleModel.articleTypeId = Convert.ToInt32(DropDownList1.SelectedItem.Value);//获取下拉框选择值

bool state = articleBll.Update(articleModel);

if (state) {

//第一种方法

//Response.Redirect("ArticleList.aspx");//成功后跳转到列表页 //第二种方法

ClientScript.RegisterStartupScript(this.GetType(), "success", "<script>alert('修改成功成功!');window.location.href='ArticleList.aspx';</script>"); //成功后提示再跳转 } }

运行效果图如下:

本文来源:https://www.bwwdw.com/article/edtj.html

Top