2014-02-18 346 views
1

我试图在我的c#窗体项目中显示datagridview中的数据。我不断收到此错误填充:SelectCommand.Connection属性尚未初始化错误

“填写:SelectCommand.Connection属性尚未初始化”

有什么我做错了这里:

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

看来,哈比卜,阿奎那和我都给你非常类似的解决方案。他们工作? –

回答

1

您必须指定一个SqlConnection对象到您的SqlCommand对象。

db.Connection = conn; 

哪里conn是你SqlConnection对象。

初始化您SqlConnection对象,像这样:

var conn = new SqlConnection(/*Connection String*/); 
相关问题