我有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]; Listrows = new List (); 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:
Listrows = new List (); 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,我强烈建议您绑定它,而不是手动填充它。
绑定也带来了额外的好处,就是您可以保持Object完好无损,例如,如果要对选定的行进行操作,则可以通过绑定DatagridView来实现:
if(gridViewParts.CurrentRow != null) { SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem); // You can use item here without problems. }
建议您绑定的类确实实现该System.ComponentModel.INotifyPropertyChanged
接口,从而允许其将更改告知网格。