How to convert datarow to datatable in c#

To convert a DataRow to a DataTable in C#, you need to create a new DataTable object and add the columns from the DataRow to the DataTable. Then you can add the DataRow’s data to the new DataTable’s rows.

Here’s an example that demonstrates the process:

    
using System;
using System.Data;

public class DataRowToDataTableExample
{
    public static void Main()
    {
        // Create a new DataTable
        DataTable dt = new DataTable();

        // Create columns in the DataTable based on the DataRow structure
        foreach (DataColumn dc in GetDataRow().Table.Columns)
        {
            dt.Columns.Add(dc.ColumnName, dc.DataType);
        }

        // Create a new DataRow
        DataRow dr = dt.NewRow();

        // Set values for the DataRow
        dr["ID"] = 1;
        dr["Name"] = "John Doe";
        dr["Age"] = 30;

        // Add the DataRow to the DataTable
        dt.Rows.Add(dr);

        // Display the DataTable
        foreach (DataRow row in dt.Rows)
        {
            foreach (DataColumn col in dt.Columns)
            {
                Console.WriteLine(col.ColumnName + ": " + row[col]);
            }
        }
    }

    // Sample method to return a DataRow with a predefined structure
    public static DataRow GetDataRow()
    {
        // Create a new DataTable
        DataTable dt = new DataTable();

        // Add columns to the DataTable
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Age", typeof(int));

        // Create a new DataRow
        DataRow dr = dt.NewRow();

        // Set values for the DataRow
        dr["ID"] = 1;
        dr["Name"] = "John Doe";
        dr["Age"] = 30;

        // Return the DataRow
        return dr;
    }
}
    
  

In this example, we create a DataTable called “dt” and add columns to it based on the structure of the DataRow returned by the GetDataRow() method. Then we create a new DataRow, set values for its columns, and add it to the DataTable using the Rows.Add() method. Finally, we display the contents of the DataTable by iterating over its rows and columns.

This demonstrates how to convert a DataRow to a DataTable in C# by creating a new DataTable object, adding columns, and copying the data from the DataRow to the DataTable.

Leave a comment