簡體   English   中英

C# Winforms 將單個對象表示為表格

[英]C# Winforms Represent a Single Object as a Table

C# Winforms。 我有一堂課。 它有一些公共成員變量。 我想在一個兩列的表中顯示類的不同成員的值。 第一列是成員名稱,第二列是值。

注意:我沒有這些集合,只有一個,所以我不想要 DataGridView。

理想情況下,我只想要一個可以將我的類綁定到的控件,然后將第一列的顯示文本更改為每個成員可讀的內容。 此外,成員的值會在程序執行期間發生變化,表也應相應更新。

我沒有看到一個方便的控件 - 或者我錯過了什么? 看起來很基本。

您的最終結果將是一個表格,其中表格中的每一行都有兩個單元格:成員名稱和值。

值可以是任何類型的對象,顯示的值必須是字符串。 如果你想以其他類型顯示一些值,然后是字符串,例如圖片、顏色、象形文字等等,你需要一些從值到 DisplayValue 的轉換。

class DisplayValue
{
    public string Description{get; set;}
    public object Value {get; set;}
    public string DisplayedValue {get {return this.Value.ToString();} }
}

所以你有一個某種類型的對象,你有一個你想要顯示的這個對象的屬性序列:

MyType myObject = ...
IEnumerable<PropertyInfo> propertiesToDisplay = typeof<MyType>.GetProperties()
    .Where(propertyInfo => propertyInfo.CanRead);

IEnumerable<DisplayValue> displayValues = propertiesToDisplay
    .Select(property => new DisplayValue()
    {
        Description = property.Name,
        Value = property.GetValue(myObject),
    });

如果您不想顯示所有屬性,而只想顯示具有特定名稱的屬性:

IEnumerable<string> propertyNames = new string[]
{
    "Id", "FirstName", "MiddleName", "LastName",
    "Street", "City", "PostCode",
};
IEnumerable<PropertyInfo> propertiesToDisplay = propertyNames
    .Select(propertyName => typeof<Student>.GetProperty(propertyName));

要在 DataGridView 中顯示它們,最簡單的方法是使用設計器:

  • 添加綁定源
  • BindingSource.DataSource = DisplayValue
  • 添加數據網格視圖
  • DataGridView.BindingSource = bindingSource1
  • 添加列:一列用於描述,一列用於 DisplayedValue

每當您准備好顯示值時,例如在加載表單時:

MyType objectToDisplay = ...
IEnumerable<PropertyInfo> propertiesToDisplay = ...
IEnumerable<DisplayValues> valuesToDisplay = propertiesToDisplay
    .Select(property => new DisplayValue()
    {
        Description = property.Name,
        Value = property.GetValue(myObject),
    });

this.BindingSource1.DataSource = new BindingList<DisplayValue>(valuesToDisplay.ToList());

這里的所有都是它的。 簡單的來吧!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM