2011-05-15 110 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