C# Fill:SelectCommand。尚未初始化连接属性错误

C# Fill:SelectCommand。尚未初始化连接属性错误,c#,sql-server,C#,Sql Server,我试图在我的c#windows窗体项目中的datagridview中显示数据。我一直在犯这个错误 “Fill:SelectCommand。连接属性尚未初始化” 我有没有做错什么: private void Form1_Load(object sender, EventArgs e) { try { SqlCommand db = new SqlCommand("select * from Tbl

我试图在我的c#windows窗体项目中的
datagridview
中显示数据。我一直在犯这个错误

“Fill:SelectCommand。连接属性尚未初始化”

我有没有做错什么:

 private void Form1_Load(object sender, EventArgs e)
        {
             try
            {

                SqlCommand db = new SqlCommand("select * from Tbls");
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = db;
                DataTable dbdataset = new DataTable();

                sda.Fill(dbdataset);
                BindingSource bsource = new BindingSource();

                bsource.DataSource = dbdataset;
                dataGridView1.DataSource = bsource;
                sda.Update(dbdataset);

            } 
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

您可以创建一个新命令:

SqlCommand db = new SqlCommand("select * from Tbls");

但是,您使用的是什么SqlConnection?你不是。您需要创建一个带有连接的命令。通常,您可以从
SqlConnection
执行此操作,请参见:

您必须将
SqlConnection
对象分配给
SqlCommand
对象

db.Connection = conn;
其中,
conn
是您的
SqlConnection
对象

db.Connection = conn;
初始化
SqlConnection
对象,如下所示:

var conn = new SqlConnection(/*Connection String*/);

哈比卜、阿奎那和我似乎都给了你们类似的解决方案。他们成功了吗?