简体   繁体   中英

How do you display data from database into datagridview in C#?

I am trying to pull data from my SQL table called CurrencyConversionAuditing but for some reason it doesn't work. I have created a button, so when I click it, it displays everything from that table.

So my code currently is:

string ConnectionString;
SqlConnection con;

ConnectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = myDatabase; Integrated Security = True"; };

private void button1_Click(object sender, EventArgs e)
{
    SqlDataAdapter sdf = new SqlDataAdapter("SELECT * FROM CurrencyConversionAuditing", con);
    DataTable sd = new DataTable();
    sdf.Fill(sd);

    dataGridView1.DataSource = sd;
}        

When I run this, the error I am getting is:

System.InvalidOperationException: 'Fill: SelectCommand.Connection property has not been initialized.'

Any help will be much appreciated.

your con object is not initialized. Make sure to initialize it first as:

con = new SqlConnection(ConnectionString); 

and you have to open the con:

con.Open(); 

and do not forget to close the con:

con.Close();

Your code should be:

string ConnectionString;
SqlConnection con;

ConnectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = myDatabase; Integrated Security = True"; };

private void button1_Click(object sender, EventArgs e)
{
    con = new SqlConnection(ConnectionString);
    con.Open();
    SqlDataAdapter sdf = new SqlDataAdapter("SELECT * FROM CurrencyConversionAuditing", con);
    DataTable sd = new DataTable();
    sdf.Fill(sd);
    con.Close();
    dataGridView1.DataSource = sd;
}    

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