将表绑定到Datagridview [英] Binding A Table To Datagridview

查看:77
本文介绍了将表绑定到Datagridview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我点击datagridview中的多行时将另一个表绑定到另一个datagridview并使用cellclick属性但它不起作用:



I want to when i click on multiple rows in datagridview bind another table to another datagridview and i use cellclick property but it does not work:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
  foreach (DataGridViewRow dr in dataGridView1.Rows)
  {
    if (dr.Cells[0].Value != null)
    {
 
       CustomerID1 = Convert.ToString(dr.Cells[1].Value);
 
      SqlConnection cnn = new SqlConnection();
      SqlCommand cmd = new SqlCommand();
 
      cnn.ConnectionString = "server=USER-VAIO\\SQLEXPRESS;database=Northwind;      integrated security=true";
      cnn.Open();
 
      cmd.Connection = cnn;
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = "select OrderID,CustomerID,OrderDate from Orders where CustomerID=@CustomerID";
 
      cmd.Parameters.Add("@CustomerID", SqlDbType.NChar).Value = CustomerID1;
 
      SqlDataReader dr1 = cmd.ExecuteReader();
      DataTable dt1 = new DataTable();
      dt1.Load(dr1);
      dataGridView2.DataSource = dt1;
 

     cnn.Close();
   }
  }
}

推荐答案

获取多个选择和单击单击的事件是不同类型的活动。



The events for getting multiple selections and cell-click are different types of events.

DataGridView.SelectionChanged Event



是为了获取所有活动SelectedRows,而




is for getting all SelectedRows, whereas

DataGridView.OnCellClick Method 



是从单个单元格,这意味着您只能获得一行和一列值。



如果您尝试将两个DataGridView链接到一个链接表中数据库,使用Visual Studio设计器使用EntityFramework创建DataSet最简单。

使用DataSet构建项目后,Forms Toolbox将使用TableAdapter绑定用户控件,如两个DataGridViews。 />


如果通过外键正确绑定它们,数据将自动更新。


is triggered from a single cell, which means you will only get one row and column value.

If you are trying to link two DataGridView to 2 linked table in a database, it's easiest to create a DataSet with EntityFramework using Visual Studio designer.
After you build the project with your DataSet, the Forms Toolbox will have TableAdapters for binding to user controls like your two DataGridViews.

If you bind them correctly via the foreign key the data will automatically update.


这篇关于将表绑定到Datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆