2015-11-21 25 views
0

我有兩個dataGridView表。其次是供應商,其次是產品。我希望他們能像這樣工作:當我點擊供應商dataGridView中的行時,在產品dataGridView中,它將只顯示來自選定供應商的產品。 這是功能我寫了這個目的:使用它在dataGridView1_CellMouseClickC#dataGridView沒有顯示我想要顯示的信息

static public void SuppliersProducts(DataGridView _productslist) 
    { 
     try 
     { 
      connection.Open(); 
      SqlCommand commandShow = new SqlCommand("SELECT a.Name FROM Products a INNER JOIN SuppliersProducts b ON a.Id = b.ProductId WHERE b.SupplierId = @SupplierId", connection); 
      DataGridViewRow dr1 = _productslist.SelectedRows[0]; 
      commandShow.Parameters.AddWithValue("@SupplierId", dr1.Cells[0].Value); 
      commandShow.ExecuteNonQuery(); 
     } 
     catch (SqlException exception) 
     { 
      MessageBox.Show(exception.ToString()); 
     } 
     finally 
     { 
      connection.Close(); 
     } 
    } 

林:

private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) 
    { 

     SuppliersProducts(ProductsList); 
    } 

凡產品列表是我的產品表中的dataGridView。問題是它沒有拋出任何錯誤,但是當我在第一個dataGridView表中點擊某個供應商時,第二個沒有任何反應。我究竟做錯了什麼?

回答

0

你可以這樣做:

變化CellMouseClick事件與CellClick因爲CellMouseClick火災時,對細胞

任何鼠標點擊按鈕和SQL Server的數據應該存儲的地方

和的ExecuteNonQuery()用於插入,刪除,更新和不返回數據的命令

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
    { 

     SuppliersProducts(ProductsList,e.RowIndex); 
    } 


static public void SuppliersProducts(DataGridView _productslist,int index) 
    { 
     try 
     { 
      connection.Open(); 

      string commandShow=String.Format("SELECT a.Name FROM Products a INNER JOIN SuppliersProducts b ON a.Id = b.ProductId WHERE b.SupplierId = {0}",_productslist.Rows[index].Cells[0].Value)); 
      //Stroing sql server data 
      var dt = new DataTable(); 
      using (var da = new SqlDataAdapter(commandShow, connection)) 
       da.Fill(dt); 
      foreach(DataRow row in dt.Rows) 
      { 
       dataGridView2.Rows.Add(row[0],...); 
      } 
     } 
     catch (SqlException exception) 
     { 
      MessageBox.Show(exception.ToString()); 
     } 
     finally 
     { 
      connection.Close(); 
     } 
    } 
+0

它說,t它不能爲dt運行foreach,因爲DataTable不包含'GetEnumerator'的公共定義 – Martin

+1

@Martin對不起,foreach(DataRow在dt.Rows中)..... – AliTheOne

+0

謝謝!有效! – Martin