您的位置:首页 > 其它

当GridView中没有数据时还显示翻页

2008-01-06 21:36 393 查看
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" EnableSortingAndPagingCallbacks="True"
OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>

</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="前一页" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="后一页" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="最后一页" />
<asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="第一页" />
</form>
</body>

后台:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewDataBind();
}

}
public void GridViewDataBind()
{
Button1.Enabled = true;
Button2.Enabled = true;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
conn.Open();
SqlDataAdapter sa = new SqlDataAdapter("select * from customers where 1=2", conn);
DataSet ds = new DataSet();
sa.Fill(ds, "customers");
if (ds.Tables[0].Rows.Count == 0)
{
AddDummyData(ds);
}
GridView1.DataSource = ds.Tables["customers"];
GridView1.AllowPaging = true;
GridView1.PageSize = 5;
GridView1.DataBind();
conn.Close();
if (GridView1.PageIndex == 0)
{
Button1.Enabled = false;
}
if (GridView1.PageIndex == GridView1.PageCount - 1)
{
Button2.Enabled = false;
}

}
catch
{

}
finally
{
conn.Close();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridViewDataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.PageIndex = GridView1.PageIndex - 1;
GridViewDataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
GridView1.PageIndex = GridView1.PageIndex + 1;
GridViewDataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.PageIndex = GridView1.PageCount - 1;
GridViewDataBind();
}
protected void Button4_Click(object sender, EventArgs e)
{
GridView1.PageIndex = 0;
GridViewDataBind();
}
private void AddDummyData(DataSet ds)
{

// Add a dummy row

DataTable dt = ds.Tables[0];

DataRow newRow = dt.NewRow();

dt.Rows.Add(newRow);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: