I created a DataBase named charityah containing 5 tables. Their names are listed in a combobox.
When I choose one of them I want to display their content in a DataGridView.
What I tried is: first I linked the DataGridView to this database and tried this code that I found:
SqlConnection connection = new SqlConnection();
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = comboBox1.Text;
connection.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Downloads\charityah.mdf;Integrated Security=True";
using (connection)
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select * from "+s, connection);
DataSet ds = new DataSet();
adapter.Fill(ds, s);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Refresh();
}
}
This method doesn't give me any errors and it finds the tables, but nothing is seen in the DataGridView.
ds.Tables[0].Rows.Countreport after theFill(ds,s)?connectioninstance, which youDispose()(viausing) every time it is used... it is guaranteed to not work the second time... (Personally, I would fix that by removing the field, and moving thenew Connection()into the method, i.e.using(var connection = new SqlConnection(cs)) {...}usingon a field, you've doomed the object atconnectionto be useless after the first time through that event handler. You can open/close things lots of times - but disposal is pretty fatal.