当当前行的两列(要添加的行)具有数据时,以下代码应该将DataGridView数据源写入分隔的文本文件。当触发CellEndEdit事件时,是否检查当前行的两列是否具有数据。
实际上,当初始当前行的两列有数据时,初始当前行不会写入分隔文本文件。
当后续当前行的两列包含数据时,后续当前行将写入分隔文本文件。
永远不会将初始当前行写入分隔的文本文件。
如何按预期将当前初始行写入目标?
private void dataGridRecord_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var currentRow = dataGridRecord.Rows[e.RowIndex];
if (currentRow.Cells.Count > 0)
{
bool partialStringRecord = false;
// Determine how many of the row's cells are empty
int emptyCells = currentRow.Cells.Cast<DataGridViewCell>()
.Count(cell => cell.Value == null || String.IsNullOrWhiteSpace(cell.Value.ToString()));
// If only one of the two cells is empty, the record is incomplete
if (emptyCells == 1) partialStringRecord = true;
// If the record is incomplete, prevent adding new rows...
if (partialStringRecord)
{
dataGridRecord.AllowUserToAddRows = false;
return;
}
// ...until the columns of the current row have data
dataGridRecord.AllowUserToAddRows = true;
// Write data table to file
var table = (DataTable)dataGridRecord.DataSource;
var records = FileManager.ToStringRecordList(table);
FileManager.SaveCsvFile(records, _fileName);
}
}
答案 0 :(得分:0)
这是我提出的解决方案:
private void dataGridRecord_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var rows = dataGridRecord.Rows;
var emptyCells = rows[e.RowIndex].Cells.Cast<DataGridViewCell>()
.Count(cell => cell.Value == null || String.IsNullOrWhiteSpace(cell.Value.ToString()));
// if there are no partial records
if (emptyCells == 0)
{
for (var i = 0; i < rows.Count; i++)
{
rows[i].DefaultCellStyle.BackColor = Color.White;
rows[i].ReadOnly = false;
}
FileManager.SaveDataTableToCsvFile(dataGridRecord, _fileName);
}
// if there are partial records
else
{
if (e.ColumnIndex != 0)
{
for (var i = 0; i < rows.Count; i++)
{
// highlight current row and disable other rows
if (rows[i] == rows[e.RowIndex])
{
rows[i].DefaultCellStyle.BackColor = Color.LightCoral;
rows[i].ReadOnly = false;
}
else if (rows[i] != rows[e.RowIndex])
{
rows[i].DefaultCellStyle.BackColor = Color.LightGray;
rows[i].ReadOnly = true;
}
}
}
else
{
FileManager.SaveDataTableToCsvFile(dataGridRecord, _fileName);
}
}
}
加载数千条记录时可能很笨重。我们会看到。