如何使用数据集填充datagridview

时间:2019-11-03 20:25:11

标签: c# sql-server database wpf visual-studio

private void Form1_Load(object sender, EventArgs e)
{
    var select = "SELECT * FROM Products";

    var c = new SqlConnection(@"Data Source=DESKTOP-4D1RO14\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"); // Your Connection String here

    var dataAdapter = new SqlDataAdapter(select, c);

    var commandBuilder = new SqlCommandBuilder(dataAdapter);
    var ds = new DataSet();
    dataAdapter.Fill(ds);

    dataGridView1.DataSource = ds.Tables[0];
}

我需要在datagridview中显示产品,然后单击一行时,它会显示供应商名称。我认为要做到这一点,我需要为产品和供应商表建立关系吗?

2 个答案:

答案 0 :(得分:0)

不一定;只要事件触发以指示当前行已更改,您就可以从网格中检索当前行,然后从基础行中检索供应商ID。但是,对于这种情况,我更喜欢使用BindingSource并连接到CurrentChanged事件。

如果将强类型数据集添加到项目中,然后将其连接到数据库并使用tableadapters和类型化数据表,您将大受青睐。完成此步骤后(将新数据集添加到项目中,打开它,右键单击表面并选择新的表适配器,填写连接详细信息,然后select * from supplers,对产品重复),您可以打开数据源窗口,将Suppliers和Products节点拖到窗体上,您将为每个节点获得一个datagridview,通过绑定源绑定到具有两个表的数据集的单个实例。然后,您可以在ProductBindingSource上对此事件处理程序进行编码:

private void ProductBindingSource_CurrentChanged(object sender, EventArgs e)
{
    if(ProductBindingSource.Current == null) return;

    var pr = (ProductBindingSource.Current as DataRowView).Row as MyDataSetName.ProductsRow;

    var ta = new SuppliersTableAdapter(); //you might even have a suppliersTableAdapter on the form; no need to make a new one if this is the case

    ta.Fill(dataset1.Suppliers, pr.SupplierID);

}

答案 1 :(得分:0)

正如您所说,您需要在两个表之间添加外键。

您可以尝试以下代码从当前datagridview中显示供应商名称。

private void Form1_Load(object sender, EventArgs e)
        {
            var select = "SELECT * FROM Product";

            var c = new SqlConnection(@""); // Your Connection String here

            var dataAdapter = new SqlDataAdapter(select, c);

            var commandBuilder = new SqlCommandBuilder(dataAdapter);
            var ds = new DataSet();
            dataAdapter.Fill(ds);

            dataGridView1.DataSource = ds.Tables[0];
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int value =Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
            SqlConnection connection = new SqlConnection(@""); // Your Connection String here
            connection.Open();
            string sql = string.Format("select SupplierName from Supplier inner join Product On Supplier.NewId = {0}", value);
            SqlCommand command = new SqlCommand(sql,connection);
            SqlDataReader reader = command.ExecuteReader();
            while(reader.Read())
            {
                textBox1.Text = reader["SupplierName"].ToString();
            }

        }

结果: enter image description here