GridControl 主从模式(Master-detail)子表格获取行数据

今天遇到一个问题,gridcontrol使用主从表的时候,在子表中获取子表的行数据时居然获取不到,郁闷了很久。然后在网上找到方法(出处在这里:https://q.cnblogs.com/q/83412/),怕那天又忘记了,所以记下来。

关键代码:

 DevExpress.XtraGrid.Views.Grid.GridView currentView = (DevExpress.XtraGrid.Views.Grid.GridView)this.gridControl1.FocusedView;
            //     DataRow focusRow = currentView.GetFocusedDataRow();
            var res = currentView.GetRow(e.RowHandle) as ClassB;
            MessageBox.Show(res.IDB);
 

  

完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitData();
        }

        private void InitData()
        {
            List<ClassA> resList = new List<ClassA>();
            for (int i = 0; i < 20; i++)
            {
                ClassA A = new ClassA();
                A.IDA = "IDA" + i;
                A.NameA = "NameA" + i;
                A.classBList = new List<ClassB>();

                for (int j = 0; j < 10; j++)
                {
                    ClassB B = new ClassB();
                    B.IDA = A.IDA;
                    B.IDB = "IDB" + j;
                    B.NameB = "NBmeB" + j;
                    A.classBList.Add(B);

                }
                resList.Add(A);
            }
            this.classABindingSource.DataSource = resList; 
            this.gridView2.CellValueChanged += GridView2_CellValueChanged; 
        }

     
        private void GridView2_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView currentView = (DevExpress.XtraGrid.Views.Grid.GridView)this.gridControl1.FocusedView;
            //     DataRow focusRow = currentView.GetFocusedDataRow();
            var res = currentView.GetRow(e.RowHandle) as ClassB;
            MessageBox.Show(res.IDB);
        }

      
    }
}
原文地址:https://www.cnblogs.com/yuanjiedao/p/10084999.html