DevExpress 控件 gridcontrol控件做主从表,如何list1绑定到gridView1和list2绑定到gridView2?

2024-10-22 15:30:10
推荐回答(1个)
回答1:

1)记录和记录绑定列表类:

using System.ComponentModel;

namespace WindowsFormsApplication1
{
    //主记录
    public class MasterRecord
    {
        public string Name { get; set; }
        public DetailRecordList DetailRecordList { get; set; }
    }
    //主记录列表(绑定列表)
    public class MasterRecordList : BindingList
    {
    }
    //从记录
    public class DetailRecord
    {
        public string Course { get; set; }
        public int Score { get; set; }
    }
    //从记录列表
    public class DetailRecordList : BindingList
    {
    }
}

2)在Form1中

using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        private MasterRecordList dataSource;

        public Form1()
        {
            InitializeComponent();
            BuildDataSource();
            //设置数据源
            gridControl1.DataSource = dataSource;
        }

         //创建数据源
        private void BuildDataSource()
        {
            dataSource = new MasterRecordList();
            
            DetailRecordList detail = new DetailRecordList();
            detail.Add(new DetailRecord() { Course = "数学", Score = 89 });
            detail.Add(new DetailRecord() { Course = "外语", Score = 79 });
            detail.Add(new DetailRecord() { Course = "化学", Score = 100 });
            dataSource.Add(new MasterRecord() { Name = "张三", DetailRecordList = detail });

            detail = new DetailRecordList();
            detail.Add(new DetailRecord() { Course = "自动控制", Score = 89 });
            detail.Add(new DetailRecord() { Course = "嵌入式系统", Score = 79 });
            detail.Add(new DetailRecord() { Course = "测试技术", Score = 100 });
            dataSource.Add(new MasterRecord() { Name = "李四", DetailRecordList = detail });
        }
    }
}

3)运行结果