Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert DataRow to an Object

Tags:

c#

object

datarow

I created a DataRow on my project:

DataRow datarow;

I want to convert this DataRow to any Type of Object. How could I do it?

like image 652
folk Avatar asked Oct 30 '13 03:10

folk


People also ask

What is a DataRow object?

A DataRowCollection object represents a collection of data rows of a data table. 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 declare a DataRow?

To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition.

How do I get a DataRow index?

Hi every one. DataRow[] dr = dt1. Select("name='" + result[k2] + "' and school='" + result1[k3] + "'");.


2 Answers

class Person{
public string FirstName{get;set;}
public string LastName{get;set;}
}

Person person = new Person();
person.FirstName = dataRow["FirstName"] ;
person.LastName = dataRow["LastName"] ;

or

Person person = new Person();
person.FirstName = dataRow.Field<string>("FirstName");
person.LastName = dataRow.Field<string>("LastName");
like image 169
Avi Fatal Avatar answered Sep 21 '22 20:09

Avi Fatal


I Have found one solution for my application.

    // function that creates an object from the given data row
    public static T CreateItemFromRow<T>(DataRow row) where T : new()
    {
        // create a new object
        T item = new T();

        // set the item
        SetItemFromRow(item, row);

        // return 
        return item;
    }

    public static void SetItemFromRow<T>(T item, DataRow row) where T : new()
    {
        // go through each column
        foreach (DataColumn c in row.Table.Columns)
        {
            // find the property for the column
            PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

            // if exists, set the value
            if (p != null && row[c] != DBNull.Value)
            {
                p.SetValue(item, row[c], null);
            }
        }
    }

This will map your DataRow to ViewModel, Like below.

Your_ViewModel model = CreateItemFromRow<Your_ViewModel>(row);
like image 31
Bharat Avatar answered Sep 19 '22 20:09

Bharat