Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataColumn Name from DataRow (not DataTable)

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?

like image 727
James Dean Avatar asked Oct 10 '12 15:10

James Dean


People also ask

How do I find my DataRow column name?

You can get the column names from DataRow by using (datarow). Table. Columns and this will return “DataColumnCollection”.

Which activity can be used to retrieve the value from a specific column from a DataRow object?

ColumnIndex - The index of the column whose value is to be retrieved from the DataRow.

What is the method used to return DataRow?

You use DataTable's NewRow method to return a DataRow object of data table, add values to the data row and add a row to the data Table again by using DataRowCollection's Add method.

How do you value a DataRow?

Just use an index to access each element. The following code would acccess the first element in the list. the name of the property you are trying to access. each datarow will maintain the schema of the datatable that it came from so you still have columns in the datarow.


2 Answers

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); } 
like image 157
Daniel Hilgarth Avatar answered Oct 08 '22 19:10

Daniel Hilgarth


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); 
like image 25
Rob Hardy Avatar answered Oct 08 '22 18:10

Rob Hardy