c# - 使用现有列将行添加到 datagridview

标签 c# winforms 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 而无需将网格绑定(bind)到 DataSource 的最快方法。绑定(bind)网格实际上会大大加快速度,如果网格中有超过 500 行,我强烈建议绑定(bind)它而不是手动填充它。

绑定(bind)也有好处,你可以保持对象完好无损,f.e.如果你想对选定的行进行操作,你可以这样做是绑定(bind)了 DatagridView:

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

建议您绑定(bind)的类实现 System.ComponentModel.INotifyPropertyChanged 接口(interface),这允许它告知网格有关更改的信息。

关于c# - 使用现有列将行添加到 datagridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/148854/

相关文章:

c++ - 在 vista+ 系统的 windows 服务中创建对话框

c# - 无法将 DateTime 的参数值从字符串转换为 Int32

c# - 链接 Linq Where 子句

c# - 有没有更有效的方法来计算减法表达式的绝对值

c# - VS2010 C# 64 位应用程序在消耗 1.5GB 内存后抛出 OutOfMemoryException

c++ - 在C++中写两个不同类型的变量

c# - 将按钮插入 NavigationViewItem UWP

c# - 覆盖 WinForms 中的事件处理程序

.net - 多 "column"DataGridView C#

c# - 如何确定哪个 DataRow 绑定(bind)到 DataGridViewRow