如何将数据绑定到两个DGV

时间:2016-03-16 10:17:18

标签: c# datagridview

我想使用数据集中的关系将来自Northwind数据库(订单)和(订单详细信息)的数据绑定到两个datagridviews,其形式为: enter image description here

表单代码为:

using System;
using System.Data;
using System.Windows.Forms;

namespace DGV_Master_Detail_Example
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


        }

        private void Form1_Load(object sender, EventArgs e)
        {
            setDataBindings();
        }

        private void setDataBindings()
        {
            DataSet dsTables = new DataSet();
            NorthwndData_ORM northData = new NorthwndData_ORM();
            DataTable dtOrders = northData.getOrders();
            DataTable dtOrderDetails = northData.getOrdersDetails();

            // Adding the tables to the data set
            dsTables.Tables.Add(dtOrders);
            dsTables.Tables.Add(dtOrderDetails);

            // Define relation between tables
            dsTables.Relations.Add("OrderDetailsRelation", dtOrders.Columns["OrderID"], dtOrderDetails.Columns["OrderID"]);

            // Create binding sources for tables
            BindingSource bindOrder = new BindingSource();
            bindOrder.DataSource = dsTables;
            bindOrder.DataMember = "dtOrders";

            BindingSource bindDetails = new BindingSource();
            bindDetails.DataSource = bindOrder;
            bindDetails.DataMember = "OrderDetailsRelation";

            // Bind data to DGVs
            dgvOrders.DataSource = bindOrder;
            dgvOrderDetails.DataSource = bindDetails;



        }

    }
}

数据和连接类是:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DGV_Master_Detail_Example
{
    class NorthwndData_ORM
    {
        // Table Orders Properties
        public int OrderID { get; set; }
        public string CustomerID { get; set; }
        public int EmployeeID { get; set; }
        public DateTime OrderDate { get; set; }
        public DateTime RequiredDate { get; set; }
        public DateTime ShippedDate { get; set; }
        public int ShipVia { get; set; }
        public decimal Freight { get; set; }
        public string ShipName { get; set; }
        public string ShipAddress { get; set; }
        public string ShipCity { get; set; }
        public string ShipRegion { get; set; }
        public string ShipPostalCode { get; set; }
        public string ShipCountry { get; set; }

        // Table Order Details Properties
        public int ProductID { get; set; }
        public decimal UnitPrice { get; set; }
        public int Quantity { get; set; }
        public float Discount { get; set; }

        private SqlConnection conn;

        private void connect()
        {
            string strCon = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
            conn = new SqlConnection(strCon);
        }

        public DataTable getOrders()
        {
            connect();
            string sqlGetOrders = "SELECT ORD.* FROM dbo.Orders AS ORD";
            DataTable dtOrders = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(sqlGetOrders, conn);

            try
            {
                conn.Open();
                sda.Fill(dtOrders);
            }
            catch (SqlException se)
            {
                MessageBox.Show(se.ToString());
            }
            finally
            {
                conn.Close();
            }
            return dtOrders;
        }

        public DataTable getOrdersDetails()
        {
            connect();
            string sqlGetOrdersDetails = "SELECT ORDL.* FROM dbo.[Order Details] AS ORDL";
            DataTable dtOrdersDetails = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(sqlGetOrdersDetails, conn);

            try
            {
                conn.Open();
                sda.Fill(dtOrdersDetails);
            }
            catch (SqlException se)
            {
                MessageBox.Show(se.ToString());
            }
            finally
            {
                conn.Close();
            }
            return dtOrdersDetails;
        }

    }
}

App.Config的内容是:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <connectionStrings>
    <add name="conStr"
         connectionString="server=OMEGA-LT\SQLEXPRESS2012; Initial catalog=Northwnd; user id=sa; password=abc123;"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

问题是在调试模式下构建和运行时没有显示错误,并且任何一个DGV中都没有显示数据。 我想我没有使用最好的绑定方法!。

1 个答案:

答案 0 :(得分:1)

我发现数据集只应该在这种情况下用于表的关系映射,而绑定的数据源应该直接链接到数据表。

因此我调整了这样的代码:

    // Create binding sources for tables
    BindingSource bindOrder = new BindingSource();
    bindOrder.DataSource = dtOrders;

    BindingSource bindDetails = new BindingSource();
    bindDetails.DataSource = bindOrder;
    bindDetails.DataMember = "OrderDetailsRelation";

它工作正常,样本运行: enter image description here