天天看点

DevExpressControl中的GridControl展现主从表数据结构

DevExpressControl中的树形控件TreeListView是用来展现层次结构的数据,但是树形控件比较适合用来展形组织架构的数据。GridControl同样可以展现层次数据结构。以下举例说明,   

以三个层级数据为例。

1、数据源必须是DataSet ds,在DataSet中添加3张表Table1,Table2,Tabl3,Table1有主键是Key1,Table2的主键是Key20,Key21、Table3的主键是Key30、Key31、Key32,添加三张表的主外键关系:

       ds.Relations.Add(“First”, Table1.Columns["Key1"], Table2.Columns["Key20"]);

ds.Relations.Add("Second", new DataColumn[] { Table2.Columns["Key20"], Table2.Columns["Key21"] },   
    new DataColumn[] { Table3.Columns["Key30"], Table3.Columns["Key31"] });
           
2、给GridControl添加三个层级的GridView,选择第一个MainGridView,点击下方的链接添加新的等级Level1,并在这个等级上分创建一个GridView1,左键点击Level1添加新等级,再创建GridView2,这样三个等级的GridView创建完成。再分别选中第一级和第二级两个GridView注册MasterRowGetLevelDefaultView事件,在相应的事件中写

            第一级的事件  e.DefaultView = GridView1;

            第二级的事件  e.DefaultView = GridView2;

3、将数据原绑定到GridControl,GridControl.DataSource=ds.Tables["Table1"];
4、展开所有子表,选中每个GridView设置DetailHeight为一个较大的数值,如10000000,调用如下方法展开所有子表

            int m_RelationIndex = 0;

private void ExpandAllRows()
        {
            for (int masteViewRowIndex = 0; masteViewRowIndex < ds.Tables["Table1"].Rows.Count; masteViewRowIndex++)
            {
                MainGridView.ExpandMasterRow(masteViewRowIndex, 0);
                ExpandChildRows(MainGridView, masteViewRowIndex);
            }
        }
 
        private void ExpandChildRows(GridView gv, int rowIndex)
        {
            GridView currentChildGV = gv.GetDetailView(rowIndex, m_RelationIndex) as GridView;
            if (currentChildGV != null)
            {
                for (int childGVRowIndex = 0; childGVRowIndex < currentChildGV.DataRowCount; childGVRowIndex++)
                {
                    ExpandChildRows(currentChildGV, childGVRowIndex);
                }
            }
            else if (currentChildGV == null && gv.CanExpandMasterRowEx(rowIndex, m_RelationIndex))
            {
                gv.SetMasterRowExpandedEx(rowIndex, m_RelationIndex, true);
                ExpandChildRows(gv, rowIndex);
            }
            else if (currentChildGV == null && !gv.CanExpandMasterRowEx(rowIndex, m_RelationIndex))
            {
                return;
            }
        }
           
5、获取选中的GridView
var focusedGridView=GridControl.FocusedView as GridView;
           
6、获取当前选中的GridView的父行,即所属行
var masterRow=m_FocusedGridView.SourceRow;
           
7、获取当前选中GridView的父GridView
var parentView= m_FocusedGridView.ParentView as GridView;