星期日, 2月 24, 2019

[EF] DataGridView 和導覽屬性 - CellFormatting Event

要在 DataGridView 上設定 DataPropertyName 屬性就可以顯示導覽屬性相關資料,為該文章 - DataGridView: How to Bind Nested Objects 的練習筆記
該圖示在 DataPropertyName 上設定 Customer.CustName
但執行時,客戶名稱顯示空白,沒有資料出現

在 CellFormatting Event 內進行變化

Order Class
namespace DataGridView4CellFormatting
{
    using System;
    using System.Collections.Generic;
    
    public partial class Order
    {
        public int OrderID { get; set; }
        public System.DateTime OrderDate { get; set; }
        public int CustID { get; set; }
    
        public virtual Customer Customer { get; set; }
    }
}
Customer Class
namespace DataGridView4CellFormatting
{
    using System;
    using System.Collections.Generic;
    
    public partial class Customer
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Customer()
        {
            this.Order = new HashSet<Order>();
        }
    
        public int CustID { get; set; }
        public string CustName { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Order> Order { get; set; }
    }
}
C# Code
using System.Data.Entity;

namespace DataGridView4CellFormatting
{
    public partial class Form1 : Form
    {
        EFDbContext context;
        BindingSource bsOrder;

        public Form1()
        {
            InitializeComponent();
            context = new EFDbContext();
            bsOrder = new BindingSource();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            context.Order.Include(c => c.Customer).Load();
            bsOrder.DataSource = context.Order.Local.ToBindingList();

            dgvOrders.AutoGenerateColumns = false;
            dgvOrders.DataSource = bsOrder;
        }

        private void dgvOrders_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            var row = dgvOrders.Rows[e.RowIndex];

            if (e.RowIndex >= 0 &&
                e.ColumnIndex == 3 &&
                row != null)
            {
                var order = (Order)row.DataBoundItem;
                if (order != null && order.Customer != null)
                {
                    e.Value = order.Customer.CustName;
                }
            }
        }
    }
}
執行結果

沒有留言:

張貼留言