Как проверить, есть ли две последовательные строки и пустые строки, пока заполненная строка не использует DataRow C #? - PullRequest
0 голосов
/ 08 мая 2018

У меня есть код, который сообщает пользователю, какие ячейки они оставили пустыми или какие строки они не заполнили, но теперь пользователи хотят, чтобы я позволил им оставить как минимум две строки EMPTY последовательно .

Поэтому мне нужно изменить код проверки для работы в следующих сценариях:

  1. Если есть только одна пустая строка, зарегистрируйте ошибку, затем перейдите к следующей строке.
  2. Если есть две последовательные пустые строки, перейдите к следующей строке, чтобы проверить, является ли она нулевой, если это нулевая ошибка журнала, если нет, выполните счастливый танец.

В приведенном ниже примере мой код подтвердит, что 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."
            });
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 13 июня 2018

Я могу предложить вам записать строки после завершения цикла следующим образом:

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()))
0 голосов
/ 08 мая 2018

Я думаю, что это решит проблему

    // 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();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...