2015-11-21 27 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