2

我在加载表单中运行此函数以将我的数据库中的信息显示到 c# 中的 dataGridView 中。问题是表单在尝试访问广告检索数据之前弹出。这是它在调试器中的运行方式。我运行下面的函数。

public void loadData()
{
    var list = mysql.Select();
    try
    {
        //start from first row
        for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            //insert IDs
            dataGridView1[0, i].Value = list[0][i];
            //insert Names
            dataGridView1[1, i].Value = list[1][i];
            for (int j = 0; j < dataGridView1.ColumnCount; j++)
            {
                if (list[3][j] != null)
                {
                    dataGridView1[j + 2, i].Value = list[3][j];
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

然后调用mysql类中的Select函数,停在MySqlDataReader处,弹出Window Form。有人能告诉我发生了什么吗?

这是 Mysql.Select()

public List <string> [] Select()
{
    string query = "SELECT id,name,weekday,description FROM employee e INNER JOIN schedule s ON e.id=s.id";

    //Create a list to store the result
    List<string>[] list = new List<string>[4];
    list[0] = new List<string>();
    list[1] = new List<string>();
    list[2] = new List<string>();
    list[3] = new List<string>();

    //Open connection
    if (this.OpenConnection() == true)
    {
        //Create Command
        MySqlCommand cmd = new MySqlCommand(query, connection);
        //Create a data reader and Execute the command
        MySqlDataReader dataReader = cmd.ExecuteReader();

        //Read the data and store them in the list
        while (dataReader.Read())
        {
            list[0].Add(dataReader["id"] + "");
            list[1].Add(dataReader["name"] + "");
            list[2].Add(dataReader["weekday"] + "");
            list[3].Add(dataReader["description"] + "");
        }

        //close Data Reader
        dataReader.Close();

        //close Connection
        this.CloseConnection();

        //return list to be displayed
        return list;
    }
    else
    {
        return list;
    }
}
4

1 回答 1

3

While its processing the MySQL command and fetching info from the Database it appears the application has been given time to paint the form.

Simple fix is to do it like this:

    private void frmMain_Load(object sender, EventArgs e)
    {
          this.visible = false;
          loadData();
          this.visible = true;
    }
于 2013-02-19T01:43:55.690 回答