首页 > 代码库 > winform 分页
winform 分页
说明:(1)如果对分页的感兴趣的话,可以看一下我传的存储过程(“SQL 存储过程 分页”)
(2)分页,第一页、上一页,下一页、最后一页只调用点击(click)事件即可;如果想要实用性的好的话,txtNowPage,需 要调用3个事件,点击事件(click)、离开事件(leave)、目标按下事件(keypress)。
效果图:
代码实现如下:
public void DataBind()
{#region 数据绑定
GetWhere();
object[] page = new object[8];
page[0] = "表或视图";
page[1] = " 字段名称 ";
page[2] = pagesize;//没有多少条记录
page[3] = nowpage;//当前页码
page[4] = strWhere;//查询条件
page[5] = "表的主键";
page[6] = sumpage;//总页数
page[7] = sizecount;//总条数
DataSet dset = new DataSet();
dset = DataAccess.GetDataSet("P_Public_Paging", true, page);
dgvMainTop.DataSource = dset.Tables[0];
sumpage = Convert.ToInt32(dset.Tables[1].Rows[0][0].ToString());
sizecount = Convert.ToInt32(dset.Tables[1].Rows[0][1].ToString());
lblSumCount.Text = "(共" + sizecount + "条记录)";
txtNowPage.Text = nowpage + "/" + sumpage;
PageState(); //分页状态
}
private void PageState()
{
#region 分页按钮状态
if (sumpage <= 1)
{
btnUp.Enabled = false;
btnNext.Enabled = false;
btnFirst.Enabled = false;
btnEnd.Enabled = false;
}
else
{
if (nowpage == 1)
{
btnFirst.Enabled = false;
btnEnd.Enabled = true;
btnUp.Enabled = false;
btnNext.Enabled = true;
}
else if (nowpage == sumpage)
{
btnUp.Enabled = true;
btnNext.Enabled = false;
btnFirst.Enabled = true;
btnEnd.Enabled = false;
}
else
{
btnUp.Enabled = true;
btnNext.Enabled = true;
btnFirst.Enabled = true;
btnEnd.Enabled = true;
}
}
#endregion
}
private void btnFirst_Click(object sender, EventArgs e)
{
#region 第一页按钮事件
DataBind();
#endregion
}
private void btnUp_Click(object sender, EventArgs e)
{
#region 上一页按钮事件
nowpage--;
DataBind();
#endregion
}
private void btnNext_Click(object sender, EventArgs e)
{
#region 下一页按钮事件
nowpage++;
DataBind();
#endregion
}
private void btnEnd_Click(object sender, EventArgs e)
{
#region 最后一页按钮事件
nowpage = sumpage;
DataBind();
#endregion
}
private void txtNowPage_KeyPress(object sender, KeyPressEventArgs e)
{
#region 页码输入限制,允许输入0-9数字 回退键 回车键
e.Handled = true;
if (e.KeyChar >= ‘0‘ && e.KeyChar <= ‘9‘ || e.KeyChar == 8)
{
e.Handled = false;
}
if (e.KeyChar == 13)
{
btnFind.Focus();
}
#endregion
}
private void txtNowPage_Leave(object sender, EventArgs e)
{
#region 设置当前页 最大为总页数 最小1
if (txtNowPage.Text == string.Empty)
{
nowpage = 1;
txtNowPage.Text = nowpage + "/" + sumpage;
}
string strpage = txtNowPage.Text.Trim();
string[] array = strpage.Split(‘/‘);
txtNowPage.Text = array[0];
int page = int.Parse(array[0]);
if (page <= 1)
{
nowpage = 1;
txtNowPage.Text = nowpage + "/" + sumpage;
}
if (page > sumpage)
{
nowpage = sumpage;
txtNowPage.Text = nowpage + "/" + sumpage;
}
if (page > 1 && page <= sumpage)
{
nowpage = page;
}
DataBind();
#endregion
}
private void txtNowPage_Click(object sender, EventArgs e)
{
#region 单击页码文本框
string strpage = txtNowPage.Text.Trim();
string[] array = strpage.Split(‘/‘);
txtNowPage.Text = array[0];
txtNowPage.Focus();
txtNowPage.SelectAll();
#endregion
}