Nick LaMarca
Nick LaMarca

Reputation: 8188

Column Does Not Belong To DataRow Exception

I am attempting to add a row of data to an empty datatable. I am getting the data for the row from another datatable.

Here is my code with comments what I am attempting to do

'create a new blank row with datatable schema 
Dim newRow As DataRow = parsedDataset.Tables("Detail").NewRow

'get data from other datatable (left out the connection details)
topDS = DAL.ExecInLineSQLQuery(sSQL, True)

For Each r As DataRow In topDS.Tables(0).Rows
    For Each col As DataColumn In topDS.Tables(0).Columns
        If parsedDataset.Tables("Detail").Columns.Contains(col.ColumnName) Then
            'An exception is being raised at this line
            newRow(col) = r(col).ToString
        End If
    Next
Next

The exception says that the col doesn't belong to table Detail even though it passed the condition.

Upvotes: 1

Views: 696

Answers (1)

Steve
Steve

Reputation: 216293

When you use the DataRow(DataColum) syntax to assign a value to a DataRow an internal method is called See http://referencesource.microsoft.com/#System.Data/data/System/Data/DataRow.cs

private void CheckColumn(DataColumn column) {
    if (column == null) {
        throw ExceptionBuilder.ArgumentNull("column");
    }

    if (column.Table != _table) {
        throw ExceptionBuilder.ColumnNotInTheTable(column.ColumnName, _table.TableName);
    }
}

As you can see, the check doesn't allow to use a column from another datatable to be used as source for the value of the row column.

You could simply use

newRow(col.ColumnName) = r(col.ColumnName).ToString

Upvotes: 1

Related Questions