简体   繁体   中英

Show MySQL database values in DataGridView C#

I made a connection to my database, but when I try to view some data from 1 table, is not showing in dataGridView . When I am pressing the button, few seconds seems like is going to show the values, and after that nothing posted in dataGridView

Can anyone explain if I made sth wrong in my code? I am working in Visual Studio 2013

My code:

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

You should set AutoGenerateColumns to true

bdsour.DataSource = dta;
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bdsour;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM