DataColumn Name from DataRow (not DataTable)

C#.NetDatarowDatacolumn

C# Problem Overview


I need to iterate the columnname and column datatype from a specific row. All of the examples I have seen have iterated an entire datatable. I want to pass a single row to a function to do a bunch of conditional processing. I want to separate the conditional processing for ease of readability.

This is what I have:

private void doMore(DataRow dr)
{
    foreach (DataColumn c in dr.ItemArray)  //loop through the columns. 
    {
        MessageBox.Show(c.ColumnName.ToString());
    }
}

The error returned is

>System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Data.DataColumn'.

How would I get the column name from the row or do I have no choice and must pass the entire datatable to the function?

C# Solutions


Solution 1 - C#

You would still need to go through the DataTable class. But you can do so using your DataRow instance by using the Table property.

foreach (DataColumn c in dr.Table.Columns)  //loop through the columns. 
{
    MessageBox.Show(c.ColumnName);
}

Solution 2 - C#

You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:

static class Extensions
{
    public static string GetColumn(this DataRow Row, int Ordinal)
    {
        return Row.Table.Columns[Ordinal].ColumnName;
    }
}

Then call it using:

string MyColumnName = MyRow.GetColumn(5);

Solution 3 - C#

You need something like this:

foreach(DataColumn c in dr.Table.Columns)
{
  MessageBox.Show(c.ColumnName);
}

Solution 4 - C#

use DataTable object instead:

 private void doMore(DataTable dt)
    {
    foreach(DataColumn dc in dt.Columns)
    {
    MessageBox.Show(dc.ColumnName);
    }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames DeanView Question on Stackoverflow
Solution 1 - C#Daniel HilgarthView Answer on Stackoverflow
Solution 2 - C#Rob HardyView Answer on Stackoverflow
Solution 3 - C#Mark HarrellView Answer on Stackoverflow
Solution 4 - C#Kamil KrasinskiView Answer on Stackoverflow