【问题标题】:Can't format columns on DataGridView bound to List<T>无法格式化绑定到 List<T> 的 DataGridView 上的列
【发布时间】:2011-01-05 17:12:23
【问题描述】:

我将对象列表绑定到 datagridview 并且显示出现问题: 这是我的自定义类

public class Line
{
    private int _sequence;
    public int Sequence {get { } set { }}

    private string _dataTime;
    public string DataTime {get { } set { }}

    private string _content;
    public string Content {get { } set { }}

    public Line(int sequence, string dateTime, string content)
    {
        _sequence = sequence;
        _dataTime = dateTime;
        _content = content;
        IsBookmarked = false;
    }
}

我绑定列表:

List<Line> lines = new List<Line>();
// lines is initialized with values

DataGridView dataGrid = new DataGridView();
dataGrid.DataSource = Lines

DataGridView 显示列表的内容没有问题。但是列很窄,所以我想格式化列:

dataGrid.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

在这里我得到一个例外:

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

在运行时检查 dataGrid.Columns.Count 我发现它是 '0' 而不是我期望的 3。

【问题讨论】:

  • 我认为您正在绑定列表并在运行时创建 gridview 对象,否则它会完美工作吗?我的意思是将网格放置在表单上,​​如果您在表单加载时为该网格编写 Autosize 代码。
  • 我正在运行时创建数据网格视图和绑定。我可以在运行时自己创建列并对其进行格式化,然后我得到这些预制列,新列显示类的属性(所以我有 6 列而不是 3 列和 3 列是空的。跨度>

标签: winforms list datagridview


【解决方案1】:

您可以尝试在网格而不是每个单独的列上设置属性:

将 DataGridView.AutoSizeColumnsMode 属性设置为 Fill 以设置所有不覆盖此值的列的大小调整模式。

from here

【讨论】:

  • 这是一个选项,但我宁愿不将所有列都设置为填充。
猜你喜欢
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 2013-10-24
  • 1970-01-01
  • 2013-05-17
  • 2018-06-28
  • 2014-05-12
相关资源
最近更新 更多