San
San

Reputation: 3

How to Insert the data from Array to DataTable using c#

I need to insert an array into a specific column of the datatable,

For example

string[] arr1 = new String[] { "a", "b", "c" };

string[] arr2 = new String[] { "d", "e", "f" };

Datatable dt = new Datatable();

dt.columns.Add("Column1");

dt.columns.Add("Column2");

Now I want to insert the 'arr1 into column1' and 'arr2 into column2'?

Column1     Column2
     a            d
     b            e
     c            f

Please anyone give me solution for this...

Upvotes: 0

Views: 4525

Answers (1)

CC Inc
CC Inc

Reputation: 5928

To add data into a DataTable, you need to create a DataRow and set the columns of the row equal to the data for that column.

DataRow row; 
var numberOfRows = 3;
for(int i = 0; i < numberOfRows; i++)
{ 
    row = dt.NewRow(); 
    if(i < arr1.Length)
        row["Column1"] = arr1[i];
    if(i < arr2.Length)
        row["Column2"] = arr2[i];
    dt.Rows.Add(row); 
} 

Upvotes: 1

Related Questions