How do I convert an object to DataRow in C#?
To convert an object to a DataRow, we will follow below steps:
-
Create a DataTable: First, we need a DataTable with columns matching the properties of the object we want to convert.
-
Map Object Properties to DataTable Columns: Iterate through the properties of the object and add them as columns to the DataTable.
-
Add Object Data to DataRow: Create a new DataRow, populate it with the values from the object's properties, and add it to the DataTable.
Sample C# program:
using System;
using System.Data;
class Program
{
static void Main(string[] args)
{
// Sample object
var person = new Person { Id = 1, Name = "Raj Kumar", Age = 35 };
// Create DataTable
var dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(int));
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));
// Convert object to DataRow
var row = dataTable.NewRow();
row["Id"] = person.Id;
row["Name"] = person.Name;
row["Age"] = person.Age;
dataTable.Rows.Add(row);
// Output
Console.WriteLine("Converted DataRow:");
foreach (DataColumn col in dataTable.Columns)
{
Console.WriteLine($"{col.ColumnName}: {row[col]}");
}
}
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Output:
Converted DataRow:
Id: 1
Name: Raj Kumar
Age: 35
Comments (0)