星期三, 12月 26, 2018

[EF] WinForm DataBinding - 手動設定 BindingSource

該篇 - [EF] WinForm DataBinding 的延伸,主要是把 BindingSource 設定,用 Code 來完成,不要用精靈來拖拉,在 bsProducts 卡關,忘記是要透過 Categories.Products 導覽屬性來找出資料,直接把 Products 塞進 bsProducts 內,造成 bsCategories 移動資料時,bsProduct 內不會作動
using System.Data.Entity;
using WinFormswithEFSample.Models;

namespace WinFormswithEFSample
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private DataBindingContext _context;

        private void Form2_Load(object sender, EventArgs e)
        {
            _context = new DataBindingContext();
            _context.Categories.Load();
            bsCategories.DataSource = _context.Categories.Local.ToBindingList();

            // bsProduct 的資料來源是 bsCategories 且 DataMember 要設定 Products Property
            bsProducts.DataSource = bsCategories;
            bsProducts.DataMember = "Products";

            dgvCategories.AutoGenerateColumns = false;
            dgvProducts.AutoGenerateColumns = false;

            bindingNavigator1.BindingSource = bsCategories;
            dgvCategories.DataSource = bsCategories;
            dgvProducts.DataSource = bsProducts;
        }
    }
}

沒有留言:

張貼留言