簡體   English   中英

C#WinForm DataGridView綁定列表中的列表

[英]c# WinForm DataGridView bind List in List

我想將列表(ProductList)綁定到DataGridView,但是一列是集合(Categories),但是DataGridView顯示“(Collection)”而不是List的內容。 我無法重寫或更改此ProductList類。 如何綁定此類別列表列?

這是綁定:

dataGridView1.AutoGenerateColumns = false;
dataGridView1.ColumnCount = model.ColumnsNames.Length;
for (int i = 0; i < model.ColumnsNames.Length; i++)
{
    string columnName = model.ColumnsNames[i];
    dataGridView1.Columns[i].Name = columnName;
    dataGridView1.Columns[i].DataPropertyName = columnName;
}
dataGridView1.DataSource = model.Products;

這是ProductModel ,網格的數據源是List<Product>

public class Product
{
    //...

    /// <summary>
    /// List of product categories names (string). 
    /// In write-mode need to pass a array of categories IDs (integer)
    /// (uses wp_set_object_terms())
    /// </summary>
    public List<object> categories { get; set; }

    // ...
}

我不想使用子網格,我只想在TextBoxColumn中以字符串形式顯示屬性,如下所示:CollectionElement1,CollectionElement2等。

這不是我的課,實際上只是參考。 因此,我無法在任何地方進行更改。

您可以使用DataGridView CellFormatting事件來提供categories屬性的友好表示形式:

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    //Use zero based index of the cell that contains categories
    var cell= 3;

    if (e.ColumnIndex == cell && e.RowIndex >= 0)
    {
        var categories = (List<object>)dataGridView1.Rows[e.RowIndex].Cells[cell].Value;
        e.Value = string.Join(", ", categories.Select(x => x.ToString()));
    }
}

在這種情況下, categories包含List of product categories names (string). 因此,選擇ToString()是可以的。 但是對於List<SomeClass> ,您應該覆蓋SomeClass ToString或選擇其屬性之一。

作為另一個選擇,您可以使用新的ViewModel或使用匿名類型來確定查詢的結果,但是在當前Product模型不屬於您並且它具有很多屬性的情況下,以前的解決方案是最簡單的選擇。

就像是

dataGridView1.DataSource = (from p in model.Products 
                            select string.Join(", ", p.categories.ToArray())).ToList();

暫無
暫無

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

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