本文介绍了将DataGridView绑定到实体的“主从细节"中.方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在两个DataGridView之间建立主从关系.我有一个EntityModel,其中两个实体通过"ClientComissions"关联连接.它们是从现有数据库生成的,并且具有导航属性,可以很好地工作.证明(使用提到的EntityModel的控制台应用程序):

I'm trying to establish a master-detail relation between two DataGridView.I have an EntityModel with two entities connected by "ClientComissions" Association.They were generated from an existing DB, and have Navigation Properties, that work well.Proof (console app using mentioned EntityModel):

            using (var context = new MnxEntities())
        {
            Client client = context.Clients.FirstOrDefault();
            // profiler: "SELECT TOP (1) ... FROM [Clients] AS [c]" - Ok!
            Console.WriteLine("Client: {0}", client.Name);
                foreach (Comission comission in client.NavComissions)
                // profiler: "SELECT ... FROM [Comissions] WHERE [StateCode] = '20971504'" - Ok!
                {
                    Console.WriteLine("Agreement number: {0}", comission.Dog_Num);
                }
        }


但是我无法在Windows窗体上以主从方式绑定两个DataGridView:


But I can't bind two DataGridViews in a master-detail manner on windows form:

        private void tabComissions_Enter(object sender, EventArgs e)
    {
        using (var context = new MnxEntities())
        {
            clientDataGridView.DataSource  = context.Clients;

            comissionsDataGridView.DataSource = clientDataGridView.DataSource;
            comissionsDataGridView.DataMember = "WHAT SHOULD BE HERE?";
        }
    }


我知道有一个BindingContext,它必须使用CurrencyManager完成所有工作,而无需手写代码.


I know there is a BindingContext, that must do all the job using CurrencyManager, with no hand-written code needed.

我在这里停留了很多时间.请帮助.

I've stuck here for to much time. Help please.

UPD:

        private void AnswerFromStackRefactored()
    {
        using (var context = new MnxEntities())
        {
            clientBindingSource.DataSource = context;
            clientBindingSource.DataMember = "Clients";

            navComissionsBindingSource.DataSource = clientBindingSource;
            navComissionsBindingSource.DataMember = "NavComissions";
        }

    }

此代码仅对网格中的第一个客户端加载一次佣金.但是,当我更改客户网格"中的当前行"时,不再需要查询数据库,并且navComissionsGrid始终显示第一个客户的佣金.:(

this code loads Comissions only once, for the first client in grid.But when I change Current row in Clients Grid there is no more query to DB and navComissionsGrid always show comission for the first client. :(

推荐答案

在窗体上拉两个ListView,并将它们分别命名为lstcategory和lstProduct.然后复制下面的代码(非常简单).您可以将相同的概念应用于您的问题.

Pull two ListViews on a Form and name them as lstcategory and lstProduct respectively. Then copy the code below [its very simple]. You may apply the same concept to your problem.

public partial class MasterDetail : Form
    {
        public MasterDetail()
        {
            InitializeComponent();
        }

        private BindingManagerBase categoryBinding;
        private DataSet ds;

        private void MasterDetail_Load(object sender, EventArgs e)
        {
            ds = GetCategoriesAndProducts();

            // Bind the lists to different tables.
            lstCategory.DataSource = ds.Tables["Categories"];
            lstCategory.DisplayMember = "CategoryName";

            lstProduct.DataSource = ds.Tables["Products"];
            lstProduct.DisplayMember = "ProductName";

            // Track the binding context and handle position changing.
            categoryBinding = this.BindingContext[ds.Tables["Categories"]];
            categoryBinding.PositionChanged += new EventHandler(Binding_PositionChanged);

            // Update child table at startup.
            UpdateProducts();
        }

        private void Binding_PositionChanged(object sender, System.EventArgs e)
        {
            UpdateProducts();
        }

        private void UpdateProducts()
        {
            string filter;
            DataRow selectedRow;

            // Find the current category row.
            selectedRow = ds.Tables["Categories"].Rows[categoryBinding.Position];

            // Create a filter expression using its CategoryID.
            filter = "CategoryID='" + selectedRow["CategoryID"].ToString() + "'";

            // Modify the view onto the product table.
            ds.Tables["Products"].DefaultView.RowFilter = filter;
        }

        public DataSet GetCategoriesAndProducts()
        {
            DataTable category = new DataTable("Categories");
            category.Columns.Add("CategoryID");
            category.Columns.Add("CategoryName");

            category.Rows.Add(new object[] { "1", "Food" });
            category.Rows.Add(new object[] { "2", "Beverage" });


            DataTable product = new DataTable("Products");
            product.Columns.Add("CategoryID");
            product.Columns.Add("ProductName");

            product.Rows.Add(new object[] { "1", "Rice" });
            product.Rows.Add(new object[] { "1", "Pasta" });

            product.Rows.Add(new object[] { "2", "Cola" });
            product.Rows.Add(new object[] { "2", "Coffee" });
            product.Rows.Add(new object[] { "2", "Tea" });


            DataSet ds = new DataSet();
            ds.Tables.Add(category);
            ds.Tables.Add(product);

            // Set up a relation between these tables (optional).
            DataRelation relCategoryProduct = new DataRelation("CategoryProduct",
              ds.Tables["Categories"].Columns["CategoryID"],
              ds.Tables["Products"].Columns["CategoryID"]);

            ds.Relations.Add(relCategoryProduct);

            return ds;
        }

    }       

这篇关于将DataGridView绑定到实体的“主从细节"中.方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 18:26