溫馨提示×

如何在C#中使用Table進(jìn)行數(shù)據(jù)分頁

c#
小樊
96
2024-08-21 09:30:30
欄目: 編程語言

在C#中使用Table進(jìn)行數(shù)據(jù)分頁通常是通過使用類似于DataGridView或者ListView這樣的控件來展示數(shù)據(jù),并且結(jié)合使用Paging類或者自定義的分頁邏輯來實(shí)現(xiàn)分頁功能。以下是一個(gè)簡單的示例:

using System;
using System.Windows.Forms;

public partial class Form1 : Form
{
    private DataTable dataTable;
    private int pageSize = 10;
    private int currentPage = 1;

    public Form1()
    {
        InitializeComponent();
        LoadData();
        DisplayData();
    }

    private void LoadData()
    {
        // Load data from database or any other source
        // For demo purpose, we will create a sample DataTable
        dataTable = new DataTable();
        // Add columns to the DataTable
        dataTable.Columns.Add("ID", typeof(int));
        dataTable.Columns.Add("Name", typeof(string));
        // Add rows to the DataTable
        for (int i = 1; i <= 100; i++)
        {
            dataTable.Rows.Add(i, "Name " + i);
        }
    }

    private void DisplayData()
    {
        // Clear existing rows in the DataGridView
        dataGridView1.Rows.Clear();
        // Calculate start and end index of the current page
        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.Min(startIndex + pageSize, dataTable.Rows.Count);
        for (int i = startIndex; i < endIndex; i++)
        {
            // Add a row to the DataGridView for each data row
            DataGridViewRow row = new DataGridViewRow();
            row.CreateCells(dataGridView1, dataTable.Rows[i]["ID"], dataTable.Rows[i]["Name"]);
            dataGridView1.Rows.Add(row);
        }
    }

    private void btnNext_Click(object sender, EventArgs e)
    {
        currentPage++;
        DisplayData();
    }

    private void btnPrevious_Click(object sender, EventArgs e)
    {
        currentPage--;
        DisplayData();
    }
}

在此示例中,我們創(chuàng)建了一個(gè)包含ID和Name列的DataTable,并填充了100條數(shù)據(jù)。然后,我們通過點(diǎn)擊“Next”和“Previous”按鈕來切換不同頁數(shù)的數(shù)據(jù)。您可以根據(jù)需要自定義分頁邏輯,并根據(jù)實(shí)際需求調(diào)整代碼。

0