首頁 > 軟體

C#對XtraGrid控制元件實現主從表關係繫結

2022-06-14 18:00:31

1、準備源資料。

/// <summary>
/// 記錄基礎資訊
/// </summary>
public class DetailInfo
{
    public DetailInfo()
    {
        this.ID = Guid.NewGuid().ToString();
    }

    /// <summary>
    /// ID標識
    /// </summary>
    public string ID { get; set; }

    /// <summary>
    /// 名稱
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 描述資訊
    /// </summary>
    public string Description { get; set; }
}

/// <summary>
/// 二級層次的列表
/// </summary>
public class Detail2Result : DetailInfo
{
    public List<DetailInfo> Detail2List { get; set; }
}

2、繫結資料來源

/// <summary>
/// 繫結資料來源
/// </summary>
private void BindData()
{
    //建立測試資料
    var result1 = new Detail2Result()
    {
        Name = "測試1",
        Description = "描述內容",
        Detail2List = new List<DetailInfo>()
        {
            new DetailInfo()
            {
                Name = "111測試",
                Description = "111描述內容"
            },
            new DetailInfo()
            {
                Name = "222測試",
                Description = "222描述內容"
            },
            new DetailInfo()
            {
                Name = "333測試",
                Description = "333描述內容"
            }
        }
    };

    var result2 = new Detail2Result()
    {
        Name = "測試2",
        Description = "描述內容",
        Detail2List = new List<DetailInfo>()
        {
            new DetailInfo()
            {
                Name = "111測試",
                Description = "111描述內容"
            },
            new DetailInfo()
            {
                Name = "222測試",
                Description = "222描述內容"
            },
            new DetailInfo()
            {
                Name = "333測試",
                Description = "333描述內容"
            }
        }
    };

    //構造一個記錄的集合
    var list = new List<Detail2Result>() { result1, result2 };

    //繫結資料來源
    this.gridControl.DataSource = list;
}

3、DevExpress的GridControl控制元件的設定

在主檢視下新增一層檢視為gridView2,並修改當前檢視的 Change LeveName 為Detail2List (如果不修改結果是資料繫結失敗)

設定gridView2屬性中的ViewCaption 屬性。

4、效果

5、子表格獲取行資料

DevExpress.XtraGrid.Views.Grid.GridView currentView = (DevExpress.XtraGrid.Views.Grid.GridView)this.gridControl.FocusedView;
DetailInfo focusRow = currentView.GetFocusedRow() as DetailInfo; //用在事件中:currentView.GetRow(e.RowHandle) as DetailInfo;
XtraMessageBox.Show(focusRow.Name);

到此這篇關於C#對XtraGrid控制元件實現主從表關係繫結的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com