无法从方法访问SqlConnection

时间:2016-04-01 17:32:33

标签: c# sql

我似乎无法从另一种方法访问我的SqlConnection。我在主窗体中创建了连接。我试图在loadAdminTable方法中重用它。

我不确定我应该包含或更改以允许在此方法中访问它。任何帮助或良好的方向都会很棒。感谢

的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");

尝试使用连接的方法

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

        }

2 个答案:

答案 0 :(得分:2)

删除你的sqlconnection& sqlcommand并将其粘贴到您的try块中。现在,每次声明SqlConnection时,都不需要明确地编写它。它将从App.Config文件中获取连接字符串。我认为这符合你的目的......

    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;

< -------将以下块添加到App.config文件----------->

<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>      

答案 1 :(得分:1)

将方法的签名更改为

public void loadAdminTable(con)

所有人都应该工作。提供您打开连接