1

I am trying to add columns to a DataTable.

I can add the columns just fine. However, when I loop through the rows setting values for these new columns, it doesn't update the DataRow.ItemArray. Here is my code:

private void UpdateTabularDataTable(SqlConnection connection)
{
      // when I add these columns, it works fine.
      var rejectedColumn = table.Columns.Add(Constants.RejectedUiColumnName, typeof(bool));
      var rejectedReasonColumn = table.Columns.Add(Constants.RejectedReasonUiColumnName, typeof(string));

      foreach (var row in table.Rows.Cast<DataRow>())
      {
        var contourId = (Guid)row.ItemArray[0];

        // this is a Dictionary of objects which are rejected.  The others are accepted.
        string rejectedReason;
        var isRejected = _rejectedParticleReasonHolder.TryGetValue(contourId.ToString(), out rejectedReason);

        // these assignments don't work.  There's no exception; they 
        // just don't update the relevant values on the object.
        // Also, I verified that the Ordinal values are correct.
        row.ItemArray[rejectedColumn.Ordinal] = isRejected;
        row.ItemArray[rejectedReasonColumn.Ordinal] = rejectedReason;

      }
    }
  }

}

2 Answers 2

3

you should change your code to look something like this

private void UpdateTabularDataTable(SqlConnection connection)
{
      table.Columns.Add(Constants.RejectedUiColumnName, typeof(bool));
      table.Columns.Add(Constants.RejectedReasonUiColumnName, typeof(string));

      foreach (var row in table.Rows.Cast<DataRow>())
      {
        var contourId = (Guid)row.ItemArray[0];

        // this is a Dictionary of objects which are rejected.  The others are accepted.
        string rejectedReason;
        var isRejected = _rejectedParticleReasonHolder.TryGetValue(contourId.ToString(), out rejectedReason);

        row[Constants.RejectedUiColumnName] = isRejected;
        row[Constants.RejectedReasonUiColumnName] = rejectedReason;

      }
    }
  }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. However, the ItemArray is just an array which is accessed by its index. I think you are confusing that syntax with the one used in the answer above. This code wouldn't compile.
Thanks didn't see that there. I've made the changes
2

One of my coworkers figured out the problem. The row.ItemArray shouldn't be accessed directly. Instead, I used row[columnName] = value to modify the column value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.