C#dataGridView不显示我想要显示的信息

时间:2015-11-21 11:35:38

标签: c# sql-server datagridview

我有两个dataGridView表。一个是供应商,第二个是产品。我希望它们像这样工作:当我点击Suppliers dataGridView中的行时,在Products 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();
       }
   }

我在dataGridView1_CellMouseClick中使用它:

 private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {

        SuppliersProducts(ProductsList);
    }

其中ProductsList是我的dataGridView for Products表。问题是它没有抛出任何错误但是当我点击我的第一个dataGridView表中的某个供应商时,第二个没有任何反应。我做错了什么?

1 个答案:

答案 0 :(得分: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();
       }
   }