我有一个代码告诉用户他们留下哪些单元格为空或他们没有填写哪些行但是现在用户希望我允许他们连续留下至少两行EMPTY。
所以我需要更改我的验证码以在这些场景中工作:
对于下面的示例,我的代码将确认ROW 3
为null并将其作为错误记录并转到下一行但它不会跳过两个连续的空行。但是我希望它跳过并转到下一行。
Row 1 | Filled
Row 2 | Filled
Row 3 |
Row 4 | Filled
Row 5 |
Row 6 |
Row 7 | Filled
foreach (DataRow row in data.Rows)
{
currentRowErrors.Clear();
if (row[0] == DBNull.Value)
{
cnt = cnt + 1;
if (cnt == 2)
{
rowCounter = rowCounter + 2;
}
}
//log errors
if (row[0] == DBNull.Value)
{
if (row[0] == DBNull.Value)
{
model.Errors.Add(new RowErrorModel()
{
Row = rowCounter,
Error = "The name cannot be blank."
});
}
}
}
我认为这样可以解决问题
// Check if datarow is empty
// dt = Datatable to be checked
// index = index of the row that will be checked
public bool isRowEmpty(DataTable dt, int index)
{
// check if index exists, if not returns false
// it will means that the row is "not empty"
if (index >= dt.Rows.Count || index < 0)
return false;
// Get row
DataRow dr = dt.Rows[index];
// Amount of empty columns
int emptyQt = 0;
// Run thourgh columns to check if any of them are empty
for (int i = 0; i < dr.ItemArray.Length; i++)
{
// If empty, add +1 to the amount of empty columns
if (string.IsNullOrWhiteSpace(dr.ItemArray[i].ToString()))
emptyQt++;
}
// if the amount of empty columns is equals to the amount of
//columns, it means that the whole row is empty
return emptyQt == dr.Table.Columns.Count;
}
public void ValidateDataRow()
{
// Run through datatable
for (int i = 0; i < dt.Rows.Count; i++)
{
// Check if the current row and the next 2 ones are empty
if (isRowEmpty(dt, i) && isRowEmpty(dt, i + 1) && isRowEmpty(dt, i + 2))
{
// Throws and alert that more than 2 rows 'in a row' are empty
Console.WriteLine("More than 2 rows are empty in a row");
// add counter by 2 because the loop will add 1 more by itselft
i += 2;
continue;
}
else
{
// Check if the previous row is filled, the current is empty and the next one is filled
// The first and the last has the operator "!" beacause if the row is empty the method to check
// Will return false, so we have to deny it
if (!isRowEmpty(dt, i- 1) && isRowEmpty(dt, i) && !isRowEmpty(dt, i + 1))
{
// Throw alert for single empty row
Console.WriteLine("Empty row" + i.ToString());
}
}
}
//DoHappyDance();
}
我可以建议你在完成循环之后记录行,如下所示:
var errorRows = new List<int>();
for (var i = 0; i < dataTable.Rows.Count; i++)
{
var row = dataTable.Rows[i];
if (row.ItemArray.All(cell => string.IsNullOrEmpty(cell.ToString())))
{
if (errorRows.Contains(i - 1))
{
// When previous row is empty remove it from list
errorRows.Remove(i - 1);
// Here also current row will not added to list
}
else
{
errorRows.Add(i);
}
}
}
log(errorRows.Select(c => (c + 1).ToString()))