문제

I have a problem.

I have two loops (one for row, one for column) for creating data in DataTable. I want to check if cell is empty for column named "Name" and if it is empty just don't add this row. And here is a question: How to cancel adding row?

Got some code:

for (int i = 0; i < data.Count(); i++)
{

    cell = data.ElementAt(i);
    DataRow row;
    row = dataTable.NewRow();

    foreach (string column in columns)
    {
        if (row["Name"] == "")
        {
            row = null;
        }
        else
        {
            row[column] = cell;
        }
    }

    if (row != null)
    {
        dataTable.Rows.Add(row);
    }
}

But after next loop is starting it throws NullException: Object reference not set to an instance of an object.

Generally I want to add Rows to DataTable only those where value of cell is not empty at column called "Name" (i mean where is "").

What is the best way or easiest way to do it right?

도움이 되었습니까?

해결책

Change it as:

....
    foreach (string column in columns)
        {
            if (row["Name"] == "")
            {
                row = null;
                break; //--> Add this line
            }
            else
            {
                row[column] = cell;
            }
        }
....
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top