【问题标题】:Datagridview row height issueDatagridview 行高问题
【发布时间】:2022-01-14 06:10:18
【问题描述】:

我最近更新了我的代码,从在 foreach 循环中使用 Rows.Add 到使用 AddRange 填充 list of rows。事实证明,这可以提高填充 datagridview 的速度(显着),但我遇到了行高问题。这不是Rows.Add 的问题,因为我可以轻松设置rowtemplate.height 属性。部分活动:

var items = listItems; int count = 1;
object[] buffer = new object[3];
List<DataGridViewRow> rows = new List<DataGridViewRow>();

foreach (var i in items)
{
buffer[0] = count;
buffer[1] = i.Desc;
buffer[2] = i.ID;

rows.Add(new DataGridViewRow());
rows[rows.Count - 1].CreateCells(datagridItems, buffer);
count++;
}
datagridItems.Rows.AddRange(rows.ToArray());

无论出于何种原因,无论rowtemplate.height 属性设置为什么,以这种方式添加行都无关紧要。我很确定这与rows.Add(new DataGridViewRow()); 有关,因为如果我尝试在AddRange 之前添加它:

    foreach (DataGridViewRow r in rows)
    {
        r.MinimumHeight = 46;
        r.Height = 46;
    }

^ 它有效。但是,我认为这不是一个好方法。所以我尝试使用new DataGridViewRow(),但到目前为止没有成功:

var items = listItems; int count = 1;
object[] buffer = new object[3];
List<DataGridViewRow> rows = new List<DataGridViewRow>();

foreach (var i in items)
{
buffer[0] = count;
buffer[1] = img;
buffer[2] = i.ID;

//rows.Add(new DataGridViewRow()); From the old example   
rows.Add(new DataGridViewRow
{
    MinimumHeight = 46,
    Height = 46
});
rows[rows.Count - 1].CreateCells(datagridItems, buffer);
count++;   
}

/* this works, but there should be a much better way of doing it
foreach (DataGridViewRow r in rows)
{
    r.MinimumHeight = 46;
    r.Height = 46
}
*/
datagridItems.Rows.AddRange(rows.ToArray());

为了记录,这些是在 datagridview 上设置的一些(可能)相关属性

//by the way, the datagridview is added in the designer
datagridItems.RowTemplate.Height = 46;
datagridItems.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
datagridItems.CellBorderStyle = DataGridViewCellBorderStyle.None;
datagridItems.RowTemplate.MinimumHeight = 46;

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    DataGridView.RowTemplate 对于您没有显式添加 DataGridViewRow 并且您只是设置数据源或传递值或传递行数的情况很有用。在您的情况下,由于您自己创建行,因此您有责任手动配置行的属性,或通过手动克隆模板来创建行。

    在以下所有示例中,RowTemplate 属性将自动用于创建行:

    • dataGridView1.DataSource = myList;
    • dataGridView1.RowCount = 5;
    • dataGridView1.Rows.Add(3);
    • dataGridView1.Rows.Add(new object[]{1, "One"});
    • dataGridView1.Rows.Insert(0, new object[]{1, "One"});

    如果你像dataGridView1.Rows.Add(myNewRow)这样添加一行,你必须自己处理myNewRow属性,例如:\

    • var myNewRow = new DataGridViewRow() {Height = 50};

    或者你可以通过克隆RowTemplate来创建myNewRow,例如:

    • var myNewRow = (DataGridViewRow)dataGridView1.RowTemplate.Clone();

    您可以通过在RowTemplate 属性的source code 中跟踪用法来了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多