向具有现有列的DataGridView添加行

8

我有一个包含多个列的 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;
}

谢谢!


我之前在这里发了一篇帖子,但已经删除了。那篇帖子与ASP.NET有关,因为我不做任何WinForms编程,所以错误地将其视为ASP.NET。如果你看到了那篇帖子并被误导了,我很抱歉。 - mattlant
2个回答

7

为了扩展这个问题,还有另一种方法可以向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 接口,以便告知网格控件有关更改的信息。

4

编辑:糟糕!第二行代码有误,已修正。

有时候,我很讨厌定义数据源属性。

我认为,每当你创建并设置一个新的“row”行时,由于某种奇怪的原因,旧值会被处理掉。尝试不使用实例来保存你创建的行:

int i;
i = gridViewParts.Rows.Add( new DataGridViewRow());

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

似乎单元格与单元格实例配合良好,但我不知道为什么对于行来说情况有所不同。可能需要进行更多测试...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接