DataGridView 分页显示

 

DataGridView 分页显示函数

 

1.获取当前页的子数据表函数

public static DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize)
{
    DataTable newdt = dt.Clone(); //复制dt数据表的架构
    int rowbegin = (PageIndex -1 ) * PageSize;
    int rowend = PageIndex * PageSize;
    
    if(rowbeign >= dt.rows.Count)
    {
        return newdt;          //起始记录行数大于等于总记录数
    }

    if(rowend > dt.Rows.Count)
    {
        rowend = dt.Rows.Count;
    }

    for(int i= rowbegin; i< rowend; i++)
    {
        DataRow newdr = newdt.NewRow();
        DataRow dr = dt.Rows[i];

        foreach(DataColumn column in dt.Columns)
        {
            newdr[column.ColumnName] = dr[column.ColumnName];
        }
        newdt.Rows.Add(newdr);
    }
    return newdt;
}

2. 调用获取子数据表函数,显示某页数据在datagridview上

SqlDataAdapter da = new SqlDataAdapter();
DataTable newdt = new DataTable();

int PageIndex = 1;
int PageSize = 10;

............

SqlCommand com = new SqlCommand("querystring",sqlconnect);
da = new SqlDataAdapter(com);
da.Fill(dt);
newdt = GetPagedTable(dt,PageIndex,PageSize);

dataGridView1.DataSource = newdt;

3. 使用NumericUpDown组件动态控制每页显示的数据记录数

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    PageIndex =1;
    PageSize = (int)numericUpDown1.Value;

    DataTable newdt = GetPagedTable(dt, PageIndex, PageSize);
    dataGridView1.DataSource = newdt;
}

 

  

你可能感兴趣的:(DataGridView 分页显示)