c# – 使用现有列向datagridview添加行

前端之家收集整理的这篇文章主要介绍了c# – 使用现有列向datagridview添加行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个DataGridView与几个创建列.我添加了一些行,它们可以正确显示;但是,当我点击一个单元格时,内容就会消失.

我究竟做错了什么?

代码如下:

foreach (SaleItem item in this.Invoice.SaleItems)
{
    DataGridViewRow row = new DataGridViewRow();
    gridViewParts.Rows.Add(row);

    DataGridViewCell cellQuantity = new DataGridViewTextBoxCell();
    cellQuantity.Value = item.Quantity;
    row.Cells["colQuantity"] = cellQuantity;

    DataGridViewCell cellDescription = new DataGridViewTextBoxCell();
    cellDescription.Value = item.Part.Description;
    row.Cells["colDescription"] = cellDescription;

    DataGridViewCell cellCost = new DataGridViewTextBoxCell();
    cellCost.Value = item.Price;
    row.Cells["colUnitCost1"] = cellCost;

    DataGridViewCell cellTotal = new DataGridViewTextBoxCell();
    cellTotal.Value = item.Quantity * item.Price;
    row.Cells["colTotal"] = cellTotal;

    DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell();
    cellPartNumber.Value = item.Part.Number;
    row.Cells["colPartNumber"] = cellPartNumber;
}

谢谢!

解决方法

只是为了扩展这个问题,还有另一种向DataGridView添加行的方法,特别是如果列总是相同的话:
object[] buffer = new object[5];
List<DataGridViewRow> rows = new List<DataGridViewRow>();
foreach (SaleItem item in this.Invoice.SaleItems)
{
    buffer[0] = item.Quantity;
    buffer[1] = item.Part.Description;
    buffer[2] = item.Price;
    buffer[3] = item.Quantity * item.Price;
    buffer[4] = item.Part.Number;

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

或者如果你喜欢ParamArrays:

List<DataGridViewRow> rows = new List<DataGridViewRow>();
foreach (SaleItem item in this.Invoice.SaleItems)
{
    rows.Add(new DataGridViewRow());
    rows[rows.Count - 1].CreateCells(gridViewParts,item.Quantity,item.Part.Description,item.Price,item.Quantity * item.Price,item.Part.Number
    );
}
gridViewParts.Rows.AddRange(rows.ToArray());

缓冲区中的值显然需要与列(包括隐藏的列)的顺序相同.

这是我发现将数据放入DataGridView而不将数据绑定到DataSource的最快方法.绑定网格实际上会加速它很长一段时间,如果你在网格中有超过500行,我强烈建议绑定它而不是手工填充它.

绑定还带有奖励,你可以保持对象的机智,例如.如果你想对所选行进行操作,你可以这样做是绑定DatagridView:

if(gridViewParts.CurrentRow != null)
{
    SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem);
    // You can use item here without problems.
}

建议您绑定的类确实实现System.ComponentModel.INotifyPropertyChanged接口,该接口允许它告知网格有关更改.

原文链接:https://www.f2er.com/csharp/101032.html

猜你在找的C#相关文章