C# — Retrieving data from MySQL and ordering them in “pages” without DataGridView

…衆ロ難τιáo~ 提交于 2019-12-02 09:50:32

In your button clicks you update the x and y values, but you never re-execute the database query or update the data on the form. You need to fetch the next "page" of data in order to display it.

First, extract your database code into a method rather than in the Load event:

private void LoadData()
{
    server = "localhost";
    database = "app";
    uid = "root";
    password = "root";
    string connectionString;
    connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
    connection = new MySqlConnection(connectionString);
    if (this.OpenConnection() == true)
    {
        string query = "SELECT * from EVENTS LIMIT"+ x +","+ y +";";
        mySqlDataAdapter = new MySqlDataAdapter(query , connection);
        ...
        ...
    }
}

Then in the Load event set your initial x and y values and load the data:

private void Form1_Load(object sender, EventArgs e)
{
    x = 0;
    y = 20;
    LoadData();
}

This should load the initial "page" of data. Then presumably you have a "next" and "previous" button for paging? Each one would increment/decrement the x and y values accordingly. Something like this:

private void nextButton_Click(object sender, EventArgs e)
{
    x += 20;
    y += 20;
    LoadData();
}

private void previousButton_Click(object sender, EventArgs e)
{
    x -= 20;
    y -= 20;
    LoadData();
}

Going further, you'll want to add some bounds checking so that people can't click "next" on the last page or "previous" on the first page. Probably some error handling would be a good idea. There are lots of ways to polish this. But the basic idea is that you need to re-query the database and re-bind the form controls with each page.

public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
    {
        LoadData(0,20);
    }
public void LoadData(int x, int y)
    {
        server = "localhost";
        database = "app";
        uid = "root";
        password = "root";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
        connection = new MySqlConnection(connectionString);
        if (this.OpenConnection() == true)
        {
            string query = "SELECT * from EVENTS LIMIT"+ x +","+ y +";";
            mySqlDataAdapter = new MySqlDataAdapter(query , connection);
            ...
            ...
        }
    }
private void button1_Click(object sender, EventArgs e)
    {
        LoadData(0,20);
    }
private void button2_Click(object sender, EventArgs e)
    {
        LoadData(20,40);
    }
 }

Call LoadData method on every button click event so that data binding takes place.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!