我写的DataGrid分页 却分不了页

yok77 2007-03-22 02:13:10
我把代码拷给大家,大家看看哪里不对?

public partial class newslist : System.Web.UI.UserControl
{
private string newTypeID;
public string NewTypeID
{
set
{
this.newTypeID = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
SqlConnection con = DB.createCon();
SqlCommand cmd = new SqlCommand("select newsTypeName from newsType where newsTypeID='" + this.newTypeID + "'", con);
con.Open();
string newTypeName = Convert.ToString(cmd.ExecuteScalar());
this.Label1.Text = newTypeName;
cmd.CommandText = "select * from newsMaster where newsTypeID='" + this.newTypeID + "'";
this.DataGrid1.DataSource = cmd.ExecuteReader();
this.DataGrid1.DataBind();
}
}
protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
this.DataGrid1.CurrentPageIndex = e.NewPageIndex;
this.DataGrid1.DataBind();
}
}
...全文
281 19 打赏 收藏 转发到动态 举报
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
yok77 2007-03-22
  • 打赏
  • 举报
回复
还是没搞定,先结了吧,我在想想.
meteoroid1984 2007-03-22
  • 打赏
  • 举报
回复
上面的 是个 类 下面的是Page_load 楼主研究一下吧
我用的是Repeater分页
yok77 2007-03-22
  • 打赏
  • 举报
回复
楼上的兄弟写得好复杂,我再研究研究,可能是我哪里写错了.
meteoroid1984 2007-03-22
  • 打赏
  • 举报
回复
我也用的用户控件 代码如下:
using System;

namespace MicMasterTest.Model
{
/// <summary>
/// Page の概要の説明です。
/// </summary>
public class Page
{
private int CurrentPage = 1;
private int TotalRecords = 0;
private int LowerBound = 0;
private int UpperBound = 0;
private int TotalPages = 1;
private int PageSize = 10;

public int TOTALPAGES
{
set
{
this.TotalPages = value;
}
get
{
return this.TotalPages;
}
}
public int LOWERBOUND
{
set
{
this.LowerBound = value;
}
get
{
return this.LowerBound;
}
}
public int UPPERBOUND
{
set
{
this.UpperBound = value;
}
get
{
return this.UpperBound;
}
}
public int TOTALRECORDS
{
set
{
this.TotalRecords = value;
}
get
{
return this.TotalRecords;
}
}
public int CURRENTPAGE
{
set
{
this.CurrentPage = value;
}
get
{
return this.CurrentPage;
}
}
public int PAGESIZE
{
get
{
return PageSize;
}
set
{
PageSize = value;
}
}

public void Recalculate()
{
TotalPages = (int)Math.Ceiling((double)TotalRecords/(double)PageSize);
LowerBound = PageSize * (CurrentPage - 1);
UpperBound = PageSize * CurrentPage - 1;

if (UpperBound >= TotalRecords)
{
UpperBound = TotalRecords - 1;
}
}
}
}




private void Page_Load(object sender, System.EventArgs e)
{
// ページを初期化するユーザー コードをここに挿入します。
this.uPager.Visible = false;
}

#region Web フォーム デザイナで生成されたコード
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: この呼び出しは、ASP.NET Web フォーム デザイナで必要です。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.btnView.Click += new System.EventHandler(this.btnView_Click);
this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
this.uPager.Paging += new MIC.RETSS.Common.Controls.PagingEventHandler(this.uPager_Paging);
this.CustomValidator1.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(this.CustomValidator1_ServerValidate);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void btnView_Click(object sender, System.EventArgs e)
{

if(Page.IsValid == true)
this.BundleTable(1);
else
this.Panel1.Visible = false;
}

//Redirect BundleEdit.aspx
private void btnNew_Click(object sender, System.EventArgs e)
{
Response.Redirect("BundleEdit.aspx?state=create");
}

private void uPager_Paging(object sender, MIC.RETSS.Common.Controls.PagingEventArgs e)
{
this.uPager.CurrentPage = e.GotoPage;
this.BundleTable(e.GotoPage);
}

private void BundleTable(int currentPage)
{

M_BUNDLE_OPERATIONS mbo = new M_BUNDLE_OPERATIONS();
BundleSql bSql = new BundleSql();
DataTable dt = new DataTable();

mbo.Bundle_cd = this.txtCD.Text;
mbo.Bundle_name = this.txtNAME.Text;
mbo.Currentpage = currentPage;

dt = bSql.BundleSelect(mbo);
mbo.Totalrecords = dt.Rows.Count;
mbo.Recalculate();
if(dt.Rows.Count > 0)
{
this.uPager.Visible = true;
this.lblMessage .Visible = false;
ArrayList ar = new ArrayList();
for(int i = mbo.Lowerbound;i<=mbo.Upperbound;i ++)
{
M_BUNDLE_OPERATIONS m = new M_BUNDLE_OPERATIONS();
if(this.chClear.Checked == true)
m.Del_type = dt.Rows[i][0].ToString();
else
m.Del_type = "";
m.Bundle_cd = dt.Rows[i][1].ToString();
m.Bundle_name = dt.Rows[i][2].ToString();
m.Apply_vol = Convert.ToInt32(dt.Rows[i][3].ToString());
m.Pt = Convert.ToDouble(dt.Rows[i][4].ToString());

ar.Add(m);
}
this.Repeater1.DataSource = ar;
this.Repeater1.DataBind();
this.uPager.CurrentPage = mbo.Currentpage;
this.uPager.TotalPages = mbo.Totalpages;
this.Panel1.Visible = true;
}
else
{
this.Panel1.Visible = false;
this.lblMessage.Visible = true;
this.lblMessage.Text = "検索条件に該当するデータは見つかりませんでした。";
}
}
yok77 2007-03-22
  • 打赏
  • 举报
回复
非常感谢romeopy(大耳朵蝈蝈)写出详细代码.

可是我还是没能实现功能,分页是能做到,但是不能点上一页和下一页...

另外我忘了说一点,我是做成的一个用户控件,是不是跟用户控件之间有关系?
meteoroid1984 2007-03-22
  • 打赏
  • 举报
回复
楼主 this.DataGrid1.DataBind(); 这句是固定写法
yok77 2007-03-22
  • 打赏
  • 举报
回复
webdiyer(www.webdiyer.com) ( ) 信誉:132 Blog 2007-03-22 14:50:05 得分: 0
问题在分页事件处理程序的代码中:
this.DataGrid1.CurrentPageIndex = e.NewPageIndex;
this.DataGrid1.DataBind();

你没有重新给DataGrid绑定数据,而只调用DataBind方法等于什么用也没有,应该把Page_Load中绑定数据的代码独立出来,在Page_Load和分页事件处理程序中都要调用这段代码,而不能只DataBind().

webdiyer能不能把绑定的那个方法写出来一下?



sq_zhuyi() ( ) 信誉:100 Blog 2007-03-22 14:56:35 得分: 0
webdiyer正解,相信lz是新手吧?

是的,才加入.net大本营.入门中...
solsolsol 2007-03-22
  • 打赏
  • 举报
回复
建议把
SqlConnection con = DB.createCon();
SqlCommand cmd = new SqlCommand("select newsTypeName from newsType where newsTypeID='" + this.newTypeID + "'", con);
con.Open();
string newTypeName = Convert.ToString(cmd.ExecuteScalar());
this.Label1.Text = newTypeName;
cmd.CommandText = "select * from newsMaster where newsTypeID='" + this.newTypeID + "'";
this.DataGrid1.DataSource = cmd.ExecuteReader();
this.DataGrid1.DataBind();

独立出来作为一个方法,比如bind(),这样在需要绑定的时候直接bind(),
romeopy 2007-03-22
  • 打赏
  • 举报
回复
后台代码改成如下

public partial class newslist : System.Web.UI.UserControl
{
private string newTypeID;
public string NewTypeID
{
set
{
this.newTypeID = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
binddate();
}
}
protected void binddate()
{
SqlConnection con = DB.createCon();
SqlCommand cmd = new SqlCommand("select newsTypeName from newsType where newsTypeID='" + this.newTypeID + "'", con);
con.Open();
string newTypeName = Convert.ToString(cmd.ExecuteScalar());
this.Label1.Text = newTypeName;
cmd.CommandText = "select * from newsMaster where newsTypeID='" + this.newTypeID + "'";
this.DataGrid1.DataSource = cmd.ExecuteReader();
this.DataGrid1.DataBind();
}
protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
this.DataGrid1.CurrentPageIndex = e.NewPageIndex;
this.binddate();
}
}
dazhong23 2007-03-22
  • 打赏
  • 举报
回复
<% @ Page Language="C#" %>
<% @ Import Namespace="System.Data" %>
<% @ Import Namespace="System.Data.OleDb" %>
<Script Language="C#" Runat="Server">
/*
Create By 飞刀
http://www.aspcn.com
2001-7-25 01:44

Support .Net Framework Beta 2
*/
OleDbConnection MyConn;
int PageSize,RecordCount,PageCount,CurrentPage;
public void Page_Load(Object src,EventArgs e)
{
//设定PageSize
PageSize = 10;

//连接语句
string MyConnString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="+Server.MapPath(".")+"..\\DataBase\\db1.mdb;";
MyConn = new OleDbConnection(MyConnString);
MyConn.Open();

//第一次请求执行
if(!Page.IsPostBack)
{
ListBind();
CurrentPage = 0;
ViewState["PageIndex"] = 0;

//计算总共有多少记录
RecordCount = CalculateRecord();
lblRecordCount.Text = RecordCount.ToString();

//计算总共有多少页
PageCount = RecordCount/PageSize;
lblPageCount.Text = PageCount.ToString();
ViewState["PageCount"] = PageCount;
}
}
//计算总共有多少条记录
public int CalculateRecord()
{
int intCount;
string strCount = "select count(*) as co from Score";
OleDbCommand MyComm = new OleDbCommand(strCount,MyConn);
OleDbDataReader dr = MyComm.ExecuteReader();
if(dr.Read())
{
intCount = Int32.Parse(dr["co"].ToString());
}
else
{
intCount = 0;
}
dr.Close();
return intCount;
}

ICollection CreateSource()
{

int StartIndex;

//设定导入的起终地址
StartIndex = CurrentPage*PageSize;
string strSel = "select * from Score";
DataSet ds = new DataSet();

OleDbDataAdapter MyAdapter = new OleDbDataAdapter(strSel,MyConn);
MyAdapter.Fill(ds,StartIndex,PageSize,"Score");

return ds.Tables["Score"].DefaultView;
}
public void ListBind()
{
score.DataSource = CreateSource();
score.DataBind();

lbnNextPage.Enabled = true;
lbnPrevPage.Enabled = true;
if(CurrentPage==(PageCount-1)) lbnNextPage.Enabled = false;
if(CurrentPage==0) lbnPrevPage.Enabled = false;
lblCurrentPage.Text = (CurrentPage+1).ToString();

}

public void Page_OnClick(Object sender,CommandEventArgs e)
{
CurrentPage = (int)ViewState["PageIndex"];
PageCount = (int)ViewState["PageCount"];

string cmd = e.CommandName;
//判断cmd,以判定翻页方向
switch(cmd)
{
case "next":
if(CurrentPage<(PageCount-1)) CurrentPage++;
break;
case "prev":
if(CurrentPage>0) CurrentPage--;
break;
}

ViewState["PageIndex"] = CurrentPage;

ListBind();

}
</script>
<html>
<head>
<title></title>
</head>
<body>
<form runat="server">
共有<asp:Label id="lblRecordCount" ForeColor="red" runat="server" />条记录 
当前为<asp:Label id="lblCurrentPage" ForeColor="red" runat="server" />/<asp:Label id="lblPageCount" ForeColor="red" runat="server" />页 

<asp:DataList id="score" runat="server"
HeaderStyle-BackColor="#aaaadd"
AlternatingItemStyle-BackColor="Gainsboro"
EditItemStyle-BackColor="yellow"
>
<ItemTemplate>
姓名:<%# DataBinder.Eval(Container.DataItem,"Name") %>
<asp:LinkButton id="btnSelect" Text="编辑" CommandName="edit" runat="server" />
</ItemTemplate>
</asp:DataList>
<asp:LinkButton id="lbnPrevPage" Text="上一页" CommandName="prev" OnCommand="Page_OnClick" runat="server" />
<asp:LinkButton id="lbnNextPage" Text="下一页" CommandName="next" OnCommand="Page_OnClick" runat="server" />

</form>
</body>
</html>
路人乙e 2007-03-22
  • 打赏
  • 举报
回复
webdiyer正解,相信lz是新手吧?
webdiyer 2007-03-22
  • 打赏
  • 举报
回复
问题在分页事件处理程序的代码中:
this.DataGrid1.CurrentPageIndex = e.NewPageIndex;
this.DataGrid1.DataBind();

你没有重新给DataGrid绑定数据,而只调用DataBind方法等于什么用也没有,应该把Page_Load中绑定数据的代码独立出来,在Page_Load和分页事件处理程序中都要调用这段代码,而不能只DataBind().
yok77 2007-03-22
  • 打赏
  • 举报
回复
allow paging的属性是true;
DataGrid->右键->属性生成器->分页->允许分页,这一步也做过了的
PagerStyle里写的上一页和下一页


我把前台代码也贴出来了:

<asp:DataGrid ID="DataGrid1" runat="server" Width="760px" AllowPaging="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" OnPageIndexChanged="DataGrid1_PageIndexChanged" PageSize="3" ShowHeader="False" AllowCustomPaging="True">
<FooterStyle BackColor="#CCCCCC" />
<SelectedItemStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" NextPageText="下一页"
PrevPageText="上一页" />
<AlternatingItemStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
·
</ItemTemplate>
</asp:TemplateColumn>
<asp:HyperLinkColumn DataNavigateUrlField="newsID" DataNavigateUrlFormatString="shownewsDetails.aspx?newsID={0}"
DataTextField="newsTitle"></asp:HyperLinkColumn>
<asp:BoundColumn DataField="upDateTime" DataFormatString="{0:D}" HeaderText="添加时间"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
rhathymia 2007-03-22
  • 打赏
  • 举报
回复
up
fuchenladenfu 2007-03-22
  • 打赏
  • 举报
回复
LS几位大大说的很清楚了
meteoroid1984 2007-03-22
  • 打赏
  • 举报
回复
把 allow paging 这个属性设置为true
xinfan 2007-03-22
  • 打赏
  • 举报
回复
DataGrid->右键->属性生成器->分页->允许分页
zhangzheng1107 2007-03-22
  • 打赏
  • 举报
回复
你allow paging了吗?
meteoroid1984 2007-03-22
  • 打赏
  • 举报
回复
看一下你的 PagerStyle 中设置的对吗?

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧