我连接了数据库,但是当我试图查看一个表中的一些数据时,它不会显示在dataGridView
中。当我按下按钮时,几秒钟后似乎会显示值,之后在dataGridView
中没有任何内容
如果我的代码出错了,有人能解释吗?
我在Visual Studio 2013工作
我的代码:
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "datasource=localhost;database=microweb;port=3306;username=root;password=pass";
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("select * from reservations", conn);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dta = new DataTable();
sda.Fill(dta);
BindingSource bdsour = new BindingSource();
bdsour.DataSource = dta;
dataGridView1.DataSource = bdsour;
sda.Update(dta);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
最佳答案
您应该将AutoGenerateColumns
设置为true
bdsour.DataSource = dta;
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bdsour;