【问题标题】:c# WinForm DataGridView bind List in Listc# WinForm DataGridView 在List中绑定List
【发布时间】:2016-11-04 14:05:31
【问题描述】:

我想将列表(ProductList)绑定到DataGridView,但是一列是集合(Categories),但是DataGridView显示“(集合)”而不是列表的内容。我无法重写或更改此 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,grid的数据源是List&lt;Product&gt;

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 等。

这不是我的课,实际上只是一个参考。所以我不能在任何地方改变它。

【问题讨论】:

  • 您的期望是什么?您想如何显示 Collection 或 List 类型的属性?如果您考虑类似Sub-GridGrid 控件具有并用于在网格中显示关系的功能,不,DataGridView 没有这样的功能。您可以购买支持此类功能的第 3 方网格控件。此外,当用户单击按钮时,您也可以使用 Button 列并打开包含该集合的表单。
  • 我不想使用子网格,我只想在 TextBoxColumn 中将属性显示为字符串,如下所示:CollectionElement1、CollectionElement2 等。
  • "公共列表 类别{ get; set; }"
  • 好吧。它不是我的课,acually只是一个参考。所以我不能在任何地方改变它。那 List 给了我一个带有字符串的列表(这是我在调试时看到的)。没有了
  • 分享模型代码。

标签: c# winforms data-binding datagridview


【解决方案1】:

您可以使用DataGridViewCellFormatting 事件来提供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&lt;SomeClass&gt; 的情况,您应该覆盖SomeClassToString 或选择其中一个属性。

作为另一种选择,您可以使用新的ViewModel 或使用匿名类型来塑造查询结果,但在当前情况下Product 模型不属于您并且它有很多属性,以前的解决方案是最简单的选择。

【讨论】:

    【解决方案2】:

    类似

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

    【讨论】:

      猜你喜欢
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      相关资源
      最近更新 更多