我有一个包含多个已创建列的 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/