c# – 使用现有列向datagridview添加行

前端之家收集整理的这篇文章主要介绍了c# – 使用现有列向datagridview添加行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个DataGridView与几个创建列.我添加了一些行,它们可以正确显示;但是,当我点击一个单元格时,内容就会消失.

我究竟做错了什么?

代码如下:

  1. foreach (SaleItem item in this.Invoice.SaleItems)
  2. {
  3. DataGridViewRow row = new DataGridViewRow();
  4. gridViewParts.Rows.Add(row);
  5.  
  6. DataGridViewCell cellQuantity = new DataGridViewTextBoxCell();
  7. cellQuantity.Value = item.Quantity;
  8. row.Cells["colQuantity"] = cellQuantity;
  9.  
  10. DataGridViewCell cellDescription = new DataGridViewTextBoxCell();
  11. cellDescription.Value = item.Part.Description;
  12. row.Cells["colDescription"] = cellDescription;
  13.  
  14. DataGridViewCell cellCost = new DataGridViewTextBoxCell();
  15. cellCost.Value = item.Price;
  16. row.Cells["colUnitCost1"] = cellCost;
  17.  
  18. DataGridViewCell cellTotal = new DataGridViewTextBoxCell();
  19. cellTotal.Value = item.Quantity * item.Price;
  20. row.Cells["colTotal"] = cellTotal;
  21.  
  22. DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell();
  23. cellPartNumber.Value = item.Part.Number;
  24. row.Cells["colPartNumber"] = cellPartNumber;
  25. }

谢谢!

解决方法

只是为了扩展这个问题,还有另一种向DataGridView添加行的方法,特别是如果列总是相同的话:
  1. object[] buffer = new object[5];
  2. List<DataGridViewRow> rows = new List<DataGridViewRow>();
  3. foreach (SaleItem item in this.Invoice.SaleItems)
  4. {
  5. buffer[0] = item.Quantity;
  6. buffer[1] = item.Part.Description;
  7. buffer[2] = item.Price;
  8. buffer[3] = item.Quantity * item.Price;
  9. buffer[4] = item.Part.Number;
  10.  
  11. rows.Add(new DataGridViewRow());
  12. rows[rows.Count - 1].CreateCells(gridViewParts,buffer);
  13. }
  14. gridViewParts.Rows.AddRange(rows.ToArray());

或者如果你喜欢ParamArrays:

  1. List<DataGridViewRow> rows = new List<DataGridViewRow>();
  2. foreach (SaleItem item in this.Invoice.SaleItems)
  3. {
  4. rows.Add(new DataGridViewRow());
  5. rows[rows.Count - 1].CreateCells(gridViewParts,item.Quantity,item.Part.Description,item.Price,item.Quantity * item.Price,item.Part.Number
  6. );
  7. }
  8. gridViewParts.Rows.AddRange(rows.ToArray());

缓冲区中的值显然需要与列(包括隐藏的列)的顺序相同.

这是我发现将数据放入DataGridView而不将数据绑定到DataSource的最快方法.绑定网格实际上会加速它很长一段时间,如果你在网格中有超过500行,我强烈建议绑定它而不是手工填充它.

绑定还带有奖励,你可以保持对象的机智,例如.如果你想对所选行进行操作,你可以这样做是绑定DatagridView:

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

建议您绑定的类确实实现System.ComponentModel.INotifyPropertyChanged接口,该接口允许它告知网格有关更改.

猜你在找的C#相关文章