首页主机资讯如何在C#中使用Table进行数据分页

如何在C#中使用Table进行数据分页

时间2024-08-21 19:44:03发布访客分类主机资讯浏览1068
导读:在C#中使用Table进行数据分页通常是通过使用类似于DataGridView或者ListView这样的控件来展示数据,并且结合使用Paging类或者自定义的分页逻辑来实现分页功能。以下是一个简单的示例: using System; usi...

在C#中使用Table进行数据分页通常是通过使用类似于DataGridView或者ListView这样的控件来展示数据,并且结合使用Paging类或者自定义的分页逻辑来实现分页功能。以下是一个简单的示例:

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();

    }

}
    

在此示例中,我们创建了一个包含ID和Name列的DataTable,并填充了100条数据。然后,我们通过点击“Next”和“Previous”按钮来切换不同页数的数据。您可以根据需要自定义分页逻辑,并根据实际需求调整代码。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 如何在C#中使用Table进行数据分页
本文地址: https://pptw.com/jishu/695096.html
C#中如何避免Table的SQL注入 C# Table与DataSet的区别是什么

游客 回复需填写必要信息