当我在窗体上拖动元素DataGridView时,绑定表列的功能被阻止。据我所知,我没有正确连接到我的数据库,但是下面的代码工作(这意味着连接已经建立)
static void Main(string[] args)
{
string connectionString = "server=localhost;user=root;database=mydatabase;password=mypassword";
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
string sql = "SELECT id, last_name FROM people WHERE id < 300";
MySqlCommand command = new MySqlCommand(sql, conn);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString() + " " + reader[1].ToString());
}
conn.Close();
}
为什么使用控制台应用程序的代码?如果要使用dataGridView,请使用表单的Load事件:
private void Form1_Load(object sender, EventArgs e)
{
string connectionString = "server=localhost;user=root;database=mydatabase;password=mypassword";
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
string sql = "SELECT id, last_name FROM people";
MySqlCommand command = new MySqlCommand(sql, conn);
MySqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
dataGridView1.Rows.Add((string)reader["id"], (string)reader["last_name"]);
i++;
}
conn.Close();
}