使用现有列将行添加到datagridview
时间:2020-03-06 14:52:34 来源:igfitidea点击:
我有一个带有几个已创建列的" 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;
}
谢谢!
解决方案
编辑:哎呀!在第二行代码上犯了一个错误。修复。
有时,我讨厌定义数据源属性。
我认为,每当我们为"行"创建并设置新行时,出于某些奇怪的原因,旧值都会被处理掉。尝试不使用实例保存我们创建的行:
int i; i = gridViewParts.Rows.Add( new DataGridViewRow()); DataGridViewCell cellQuantity = new DataGridViewTextBoxCell(); cellQuantity.Value = item.Quantity; gridViewParts.Rows[i].Cells["colQuantity"] = cellQuantity;
似乎单元格可以与单元格实例正常工作。我不知道为什么行的区别。可能需要更多测试...
只是为了扩展这个问题,还有另一种向" 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接口,该接口可将更改告知网格。

