Reputation: 306
i cant seem to access my SqlConnection from another method. I have the connection creation with in the main form. I am trying to reuse it in the loadAdminTable method.
I am unsure what i should be including or changing to allow it to be accessed in this method. Any help or good direction will be great. Thanks
MainForm
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
Method trying to use the connection
public void loadAdminTable()
{
SqlCommand cmdDatabase1 = new SqlCommand("Select * from Admin", con);
try
{
SqlDataAdapter sda1 = new SqlDataAdapter();
sda1.SelectCommand = cmdDatabase1;
DataTable dbdataset1 = new DataTable();
sda1.Fill(dbdataset1);
BindingSource bSource1 = new BindingSource();
bSource1.DataSource = dbdataset1;
adminGridView.DataSource = bSource1;
sda1.Update(dbdataset1);
adminGridView.Columns[0].Width = 92;
adminGridView.Columns[1].Width = 200;
adminGridView.Columns[2].Width = 180;
adminGridView.Columns[3].Width = 180;
adminGridView.Columns[4].Width = 170;
adminGridView.Columns[5].Width = 130;
adminGridView.Columns[6].Width = 170;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Upvotes: 0
Views: 76
Reputation: 633
Remove your sqlconnection & sqlcommand and paste it in your try block. Now every-time you declare SqlConnection you need not write it explicitly. It will get connection string from App.Config file. I think it will serve your purpose....
SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString);
conn.Open();
string query = ""Select * from Admin"";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
BindingSource bSource1 = new BindingSource();
bSource1.DataSource = dbdataset1;
adminGridView.DataSource = bSource1;
sda1.Update(dbdataset1);
adminGridView.Columns[0].Width = 92;
adminGridView.Columns[1].Width = 200;
adminGridView.Columns[2].Width = 180;
adminGridView.Columns[3].Width = 180;
adminGridView.Columns[4].Width = 170;
adminGridView.Columns[5].Width = 130;
adminGridView.Columns[6].Width = 170;
<------- Add this below block to App.config file----------->
<connectionStrings>
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True" />
</connectionStrings>
Upvotes: 2
Reputation: 5550
Change the signature of the method to
public void loadAdminTable(con)
and all should work. Providing you open the connection
Upvotes: 1