我有一个DataGridView与几个创建列.我添加了一些行,它们可以正确显示;但是,当我点击一个单元格时,内容就会消失.
@H_502_2@我究竟做错了什么?
@H_502_2@代码如下:
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; }@H_502_2@谢谢!
解决方法
只是为了扩展这个问题,还有另一种向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());@H_502_2@或者如果你喜欢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());@H_502_2@缓冲区中的值显然需要与列(包括隐藏的列)的顺序相同. @H_502_2@这是我发现将数据放入DataGridView而不将数据绑定到DataSource的最快方法.绑定网格实际上会加速它很长一段时间,如果你在网格中有超过500行,我强烈建议绑定它而不是手工填充它. @H_502_2@绑定还带有奖励,你可以保持对象的机智,例如.如果你想对所选行进行操作,你可以这样做是绑定DatagridView:
if(gridViewParts.CurrentRow != null) { SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem); // You can use item here without problems. }@H_502_2@建议您绑定的类确实实现System.ComponentModel.INotifyPropertyChanged接口,该接口允许它告知网格有关更改.