Domanda

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?

È stato utile?

Soluzione

Change it as:

....
    foreach (string column in columns)
        {
            if (row["Name"] == "")
            {
                row = null;
                break; //--> Add this line
            }
            else
            {
                row[column] = cell;
            }
        }
....
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top