2011-05-15 84 views
-1

我有与combobox控件连接的DatagridView。组合框用于过滤来自表格的数据。 Datagridview中的组合框和数据来自同一个表。我寻找错误,但找不到。它说: 不正确的语法靠近System.Data.DataRowVievSystem.Data.DataRowViev附近的语法不正确

我点击确定按钮,然后其他错误: 连接未关闭。连接的当前状态是打开的。 请帮助

 private void VraboteniPoOpstini_Load(object sender, EventArgs e) 
     { 

      try 
      { 
       con.Open(); 
       ad = new System.Data.SqlClient.SqlDataAdapter("Select * from tbl_PersonalniPodatoci ", con); 
       ds = new DataSet(); 


       ad.Fill(ds, "tbl_PersonalniPodatoci"); 
       dt = ds.Tables["tbl_PersonalniPodatoci"]; 
       con.Close(); 

       //fill combobox 
       cbOpstini.DataSource = dt; 
       cbOpstini.DisplayMember = "Opstina"; 
       cbOpstini.ValueMember = "Sifra"; 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message, "ГРЕШКА", MessageBoxButtons.OK); 
      } 

     } 


     private void cbOpstini_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      string izberiOpstina = cbOpstini.SelectedValue.ToString(); 
      string sSql; 
      try 
      { 
       con.Open(); 
       //datagridview 
       sSql = "Select Sifra, Prezime, Ime, Opstina From tbl_PersonalniPodatoci Where Opstina'" + izberiOpstina + "' Order by Sifra"; 
       ad = new System.Data.SqlClient.SqlDataAdapter(sSql, con); 
       SqlCommandBuilder cb = new SqlCommandBuilder(ad); 
       DataTable dt = new DataTable(); 
       ad.Fill(dt); 

       con.Close(); 

       // fill datagridview 
       grdOpstini.DataSource= dt; 


      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message, "ГРЕШКА", MessageBoxButtons.OK); 
      } 


     } 
+2

“不正确的语法”是的,你的代码在哪里? – BoltClock 2011-05-15 07:23:51

+0

请仅发布相关代码! – 2011-05-15 07:43:26

回答

0

正如亨克已经说 - 你需要采取更多的照顾你的连接,如何打开和关闭它们。另外:如果您使用SqlDataAdapter,则不需要手动打开连接并再次关闭连接 - 数据适配器将自动为您执行此操作。

还有:在第一个例子中,您只需要一个数据表,但是您创建了一个数据集,然后从中提取表 - 这完全是不必要的开销。

尝试这样:

private void VraboteniPoOpstini_Load(object sender, EventArgs e) 
{ 
    try 
    { 
     // add a "using System.Data.SqlClient" to your file, to make this simpler 
     ad = new SqlDataAdapter("Select * from tbl_PersonalniPodatoci ", con); 

     DataTable dt = new DataTable(); 
     ad.Fill(dt); 

     //fill combobox 
     cbOpstini.DataSource = dt; 
     cbOpstini.DisplayMember = "Opstina"; 
     cbOpstini.ValueMember = "Sifra"; 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message, "ГРЕШКА", MessageBoxButtons.OK); 
    } 
} 

你的第二个查询(使用SqlDataAdapter的等时使用DataTable向右走,无需打开和关闭的SqlConnection)你可以做一个类似的方法。

+0

我试图找到错误,像在sql查询中添加,现在没有任何错误。但仍然不起作用。我无法将我的组合框控件与DatagridView连接起来。 – user749113 2011-05-15 22:12:51