Nac*_*cho 8 c# datagridview winforms
我有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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
只是为了扩展这个问题,还有另一种方法将行添加到中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());
Run Code Online (Sandbox Code Playgroud)
或者,如果您喜欢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());
Run Code Online (Sandbox Code Playgroud)
显然,缓冲区中的值必须与列(包括隐藏列)的顺序相同。
这是我发现DataGridView无需将网格与绑定就可以将数据获取到的最快方法DataSource。绑定网格实际上将大大加快时间,并且如果网格中的行数超过500,我强烈建议您绑定它,而不是手动填充它。
绑定也带来了额外的好处,就是您可以保持Object完好无损,例如,如果要对选定的行进行操作,则可以通过绑定DatagridView来实现:
if(gridViewParts.CurrentRow != null)
{
SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem);
// You can use item here without problems.
}
Run Code Online (Sandbox Code Playgroud)
建议您绑定的类确实实现该System.ComponentModel.INotifyPropertyChanged接口,从而允许其将更改告知网格。
小智 4
编辑:哎呀!第二行代码出错了。- 修复。
有时,我讨厌定义数据源属性。
我认为每当您为“行”创建并设置新行时,出于某种奇怪的原因,旧值都会被处理。尝试不使用实例来保存您创建的行:
int i;
i = gridViewParts.Rows.Add( new DataGridViewRow());
DataGridViewCell cellQuantity = new DataGridViewTextBoxCell();
cellQuantity.Value = item.Quantity;
gridViewParts.Rows[i].Cells["colQuantity"] = cellQuantity;
Run Code Online (Sandbox Code Playgroud)
看起来单元格与单元格实例配合得很好。我不知道为什么行不同。可能需要更多测试...