您的位置:首页 > 其它

DataList嵌套,分页,点击父DataList标题在子DataList显示相关的内容,点击子DataList标题显示主要内容.

2007-04-13 09:54 441 查看
这里例子结合了DataList的分页和嵌套,还有点击显示相对内容的关联。

HTML代码:

<%@ Page language="c#" Codebehind="DataListNews.aspx.cs" AutoEventWireup="false" Inherits="DataListNesting.DataListNews" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DataList嵌套,分页,点击标题显示内容</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<style>BODY { FONT-SIZE: 12px }
A:link { TEXT-DECORATION: none }
A:visited { TEXT-DECORATION: none }
</style>
<script language="JavaScript">
scores = new Array(20);
var numTotal=0;
NS4 = (document.layers) ? 1 : 0;
IE4 = (document.all) ? 1 : 0;
ver4 = (NS4 || IE4) ? 1 : 0;
/*if (ver4) {
with (document) {
write("<STYLE TYPE='text/css'>");
if (NS4) {
write(".parent {position:absolute; visibility:visible}");
write(".child {position:absolute; visibility:visible}");
write(".regular {position:absolute; visibility:visible}")
}
else {
write(".child {display:none}")
}
write("</STYLE>");
}
}*/

function getIndex(el)
{
ind = null;
for (i=0; i<document.layers.length; i++)
{
whichEl = document.layers[i];
if (whichEl.id == el) {
ind = i;
break;
}
}
return ind;
}

function arrange()
{
nextY = document.layers[firstInd].pageY+document.layers[firstInd].document.height;
for (i=firstInd+1; i<document.layers.length; i++)
{
whichEl = document.layers[i];
if (whichEl.visibility != "hide")
{
whichEl.pageY = nextY;
nextY += whichEl.document.height;
}
}
}

function initIt()
{
if (!ver4) return;
if (NS4)
{
for (i=0; i<document.layers.length; i++)
{
whichEl = document.layers[i];
if (whichEl.id.indexOf("Child") != -1) whichEl.visibility = "hide";
}
arrange();
}
else
{
divColl = document.all.tags("DIV");
for (i=0; i<divColl.length; i++)
{
whichEl = divColl(i);
if (whichEl.className == "child") whichEl.style.display = "none";
}
}
}

function expandIt(el)
{
if (!ver4) return;
if (IE4)
{
whichEl1 = eval(el + "Child");
for(i=0;i<=numTotal-1;i++)
{
whichEl = eval(scores[i] + "Child");
if(whichEl!=whichEl1)
{
whichEl.style.display = "none";
}
}
whichEl1 = eval(el + "Child");
if (whichEl1.style.display == "none")
{
whichEl1.style.display = "block";
}
else
{
whichEl1.style.display = "none";
}
}
else
{
whichEl = eval("document." + el + "Child");
for(i=0;i<=numTotal-1;i++)
{
whichEl = eval("document." + scores[i] + "Child");
if(whichEl!=whichEl1)
{
whichEl.visibility = "hide";
}
}
if (whichEl.visibility == "hide")
{
whichEl.visibility = "show";
}
else
{
whichEl.visibility = "hide";
}
arrange();
}
}
onload = initIt;
</script>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<table align="center" border="1" width="90%" style="BORDER-COLLAPSE: collapse" borderColor="#cccccc">
<tr>
<td align="center" height="30"><font style="FONT-WEIGHT: bold; FONT-SIZE: 11pt">DataList嵌套,分页,点击标题显示内容</font></td>
</tr>
<TR>
<TD style="HEIGHT: 15px" align="center"><font style="FONT-SIZE: 10pt">共</font>
<asp:label id="lbTotalPage" runat="server"></asp:label><font style="FONT-SIZE: 10pt">页/共</font>
<asp:label id="lbTotalCount" runat="server"></asp:label><font style="FONT-SIZE: 10pt">记录 
当前</font>
<asp:label id="lbCurrentPage" runat="server"></asp:label><font style="FONT-SIZE: 10pt">页</font>          
<font style="FONT-SIZE: 10pt">跳转到</font>
<asp:dropdownlist id="ddlPage" runat="server" Width="65px" AutoPostBack="True"></asp:dropdownlist><font style="FONT-SIZE: 10pt">页</font></TD>
</TR>
<tr>
<td align="center">
<asp:DataList id="dlParent" runat="server" DataKeyField="ClassId" Width="70%">
<AlternatingItemStyle Font-Size="X-Small"></AlternatingItemStyle>
<ItemStyle Font-Size="X-Small" HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<DIV id="KB1Parent" style="MARGIN-BOTTOM: 0px"><A id="aurl" onclick="expandIt('KB1');return false" href="javascript:void(0);" runat="server"><FONT style="FONT-SIZE: 14px"><%# DataBinder.Eval(Container.DataItem,"ClassName") %>
<asp:Label id="lbCount" runat="server"></asp:Label></FONT></A></DIV>
<DIV class="child" id="KBChild" runat="server">
<asp:DataList id="dlChild" runat="server" ShowHeader="False" ShowFooter="False" RepeatDirection="Horizontal"
RepeatColumns="3">
<ItemTemplate>
  <a target=_blank href='<%# "ShowInfo.aspx?Id=" + DataBinder.Eval(Container.DataItem,"Id") %>'><FONT style="FONT-SIZE: 12px"><%# DataBinder.Eval(Container.DataItem,"Name") %></FONT></a>  
</ItemTemplate>
</asp:DataList></DIV>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
<tr>
<TD height="30" align="center">
<asp:linkbutton id="FirstPage" runat="server" CssClass="pageLinks" CommandName="First" Text="[First Page]"
OnCommand="NavigationLink_Click">
<font style="FONT-SIZE: 10pt">第一页</font></asp:linkbutton>   
<asp:linkbutton id="PreviousPage" runat="server" CssClass="pageLinks" CommandName="Prev" Text="[Previous Page]"
OnCommand="NavigationLink_Click">
<font style="FONT-SIZE: 10pt">上一页</font></asp:linkbutton>   
<asp:linkbutton id="NextPage" runat="server" CssClass="pageLinks" CommandName="Next" Text="[Next Page]"
OnCommand="NavigationLink_Click">
<font style="FONT-SIZE: 10pt">下一页</font></asp:linkbutton>   
<asp:LinkButton id="LastPage" runat="server" CssClass="pageLinks" CommandName="Last" Text="[Last Page]"
OnCommand="NavigationLink_Click">
<font style="FONT-SIZE: 10pt">末一页</font></asp:LinkButton></TD>
</tr>
</table>
</form>
</body>
</HTML>

CS代码:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace DataListNesting
{
/// <summary>
/// DataListNews 的摘要说明。
/// </summary>
public class DataListNews : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lbTotalPage;
protected System.Web.UI.WebControls.Label lbTotalCount;
protected System.Web.UI.WebControls.Label lbCurrentPage;
protected System.Web.UI.WebControls.DropDownList ddlPage;
protected System.Web.UI.WebControls.DataList dlParent;
protected System.Web.UI.WebControls.LinkButton FirstPage;
protected System.Web.UI.WebControls.LinkButton PreviousPage;
protected System.Web.UI.WebControls.LinkButton NextPage;
protected System.Web.UI.WebControls.LinkButton LastPage;
private Int32 CurrentPageNumber=1;
private int PageSize=5;
private string strConn="server=localhost;uid=sa;pwd=;database=AspNetTest";
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindData();
}
}

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.dlParent.ItemDataBound += new System.Web.UI.WebControls.DataListItemEventHandler(this.dlParent_ItemDataBound);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private DataSet BindParent(int PageSize,int CurrentPageNumber)
{
SqlConnection Conn=new SqlConnection(strConn);
SqlCommand Cmd=new SqlCommand();
Cmd.Connection=Conn;
Cmd.CommandType=CommandType.StoredProcedure;
Cmd.CommandText="BindNews";
SqlParameter pramsPageSize=new SqlParameter();
pramsPageSize.ParameterName="@PageSize";
pramsPageSize.Value=PageSize;

SqlParameter pramsCurrent=new SqlParameter();
pramsCurrent.ParameterName="@PageIndex";
pramsCurrent.Value=CurrentPageNumber;

SqlParameter pramsDocount=new SqlParameter();
pramsDocount.ParameterName="@Docount";
pramsDocount.Value=false;

Cmd.Parameters.Add(pramsCurrent);
Cmd.Parameters.Add(pramsDocount);
Cmd.Parameters.Add(pramsPageSize);
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=Cmd;
DataSet ds=new DataSet();
Conn.Open();
da.Fill(ds);
Conn.Close();
ViewState["Count"]=ds.Tables[0].Rows.Count.ToString();
return ds;
}

private void dlParent_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
{
if(e.Item.ItemIndex!=-1)
{
int ClassID=int.Parse(dlParent.DataKeys[e.Item.ItemIndex].ToString());
DataSet ds=BindChild(ClassID);
Label lb=(Label)e.Item.FindControl("lbCount");
lb.Text=" (" + ds.Tables[0].Rows.Count.ToString() + ") ";
DataList list=(DataList)e.Item.FindControl("dlChild");
list.DataSource=ds.Tables[0].DefaultView;
list.DataBind();
HtmlAnchor hr=(HtmlAnchor)e.Item.FindControl("aurl");
HtmlGenericControl dv=(HtmlGenericControl)e.Item.FindControl("KBChild");
hr.ID="KB";
string ss="expandIt('dlParent__ctl"+e.Item.ItemIndex+"_"+hr.ID+"')";
hr.Attributes.Add("onclick",ss.ToString());
dv.ID=hr.ID+"Child";
string scripts="<script>numTotal=" + int.Parse(ViewState["Count"].ToString()) +";";
for(int i=0;i<int.Parse(ViewState["Count"].ToString());i++)
{
scripts +="scores[" + i + "]='dlParent__ctl" + i + "_" + hr.ID + "';";
}
scripts +="</script>";
Page.RegisterStartupScript("scripts",scripts.ToString());
}
}

private DataSet BindChild(int ClassID)
{
SqlConnection Conn=new SqlConnection(strConn);
SqlCommand Cmd=new SqlCommand("select * from NewsInfo where ClassID="+ClassID+"",Conn);
SqlDataAdapter da=new SqlDataAdapter();
da.SelectCommand=Cmd;
DataSet ds=new DataSet();
Conn.Open();
da.Fill(ds);
Conn.Close();
return ds;
}


protected void NavigationLink_Click ( Object sender, CommandEventArgs e )//此事件为HTML代码里注册(事件为OnCommand)
{
switch ( e.CommandName )//根据设置的CommandName属性判断
{
case "First":
CurrentPageNumber = 1;
break;
case "Last":
CurrentPageNumber = Int32.Parse ( lbTotalPage.Text );
break;
case "Next":
CurrentPageNumber = Int32.Parse ( lbCurrentPage.Text ) + 1;
break;
case "Prev":
CurrentPageNumber = Int32.Parse ( lbCurrentPage.Text ) - 1;
break;
}
BindData();

}

public Int32 GetPCount()
{
SqlConnection Conn=new SqlConnection(strConn);
SqlCommand Cmd=new SqlCommand();
Cmd.Connection=Conn;
Cmd.CommandType=CommandType.StoredProcedure;
Cmd.CommandText="BindNews";
SqlParameter pramsPageSize=new SqlParameter();
pramsPageSize.ParameterName="@PageSize";
pramsPageSize.Value=1;

SqlParameter pramsCurrent=new SqlParameter();
pramsCurrent.ParameterName="@PageIndex";
pramsCurrent.Value=1;

SqlParameter pramsDocount=new SqlParameter();
pramsDocount.ParameterName="@Docount";
pramsDocount.Value=false;

Cmd.Parameters.Add(pramsCurrent);
Cmd.Parameters.Add(pramsDocount);
Cmd.Parameters.Add(pramsPageSize);
Conn.Open();
Int32 Tcount=Int32.Parse(Cmd.ExecuteScalar().ToString());
Conn.Close();
return Tcount;
}

public void BindData()
{
lbCurrentPage.Text = CurrentPageNumber.ToString();

//绑定DATAGRID
DataSet ds=BindParent(PageSize,CurrentPageNumber);
dlParent.DataSource=ds.Tables[0].DefaultView;
dlParent.DataBind();

Double TotalPages = 1;//初始化,总页数为1
Double ModePages=0;//取模余数(判断总页数是否要加1)

Int32 TotalRecords = GetPCount();//调用上面的得到总记录数的方法
TotalPages = TotalRecords / PageSize;//得到总页数(总记录数除以每页的记录数)
ModePages=TotalRecords%PageSize;//得到取模的余数(总记录数取模每页的记录数)
if(ModePages>0)//如果取模数不等于0,则把总页数加1
{
TotalPages+=1;
}
if(ModePages==0)//如果取模数等于0,不做任何事(也可以不用判断)
{
}
if(TotalPages==0)
{
TotalPages=1;
}
lbTotalPage.Text = TotalPages.ToString();//显示页面上的总页数
lbTotalCount.Text=TotalRecords.ToString();//显示页面上的总记录数

//以下为判断点击的按钮(第一页,上一页,下一页,末一页)是否可以用
if ( CurrentPageNumber == 1 )
{
PreviousPage.Enabled = false;
FirstPage.Enabled=false;
if ( TotalPages > 1 )
{
NextPage.Enabled = true;
LastPage.Enabled=true;
}
else
{
NextPage.Enabled = false;
LastPage.Enabled=false;
}
}
else
{
PreviousPage.Enabled = true;
FirstPage.Enabled=true;

if ( CurrentPageNumber == TotalPages )
{
NextPage.Enabled = false;
LastPage.Enabled=false;
}
else
{
NextPage.Enabled = true;
LastPage.Enabled=true;
}
}

ddlPage.Items.Clear();//清楚跳转的页数(如果不清除,里面的记录将会循环增加)
int PCount=int.Parse(lbTotalPage.Text);//得到总页数,为了循环
if(PCount==0)
{
PCount=1;
}
for(int i=1;i<=PCount;i++)
{
ddlPage.Items.Add(i.ToString());
}
ddlPage.Items.FindByText(CurrentPageNumber.ToString()).Selected=true;//把当前页显示在列表框的第一个

}

private void ddlPage_SelectedIndexChanged(object sender, System.EventArgs e)
{
int PageSize=int.Parse(ddlPage.SelectedValue.ToString());
int PageCount=Int32.Parse(lbTotalPage.Text.Trim().ToString());
if(PageSize<1)
{
CurrentPageNumber=1;
}
else if(PageSize>PageCount)
{
CurrentPageNumber=PageCount;
}
else
{
CurrentPageNumber=PageSize;
}
BindData();
}
}
}

注意:在CS文件里开始设置PageSize为每页显示的记录,例子里设置的是5条,可以按照自己的要求修改,
下载例子里有一个DataBase文件夹,里面有数据库ACCESS,你可以导入到SQL中,然后运行文本文件里的分页存储过程,然后修改一下CS文件里的连接字符串即可运行 ,有什么不足的地方请大家指教。
例子下载:/Files/sunnystar365/DataListNesting.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐