天天看點

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;