简体   繁体   中英

DataRow - How to cancel adding row to datatable?

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;
            }
        }
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM