Patan
Patan

Reputation: 17873

how to read data from data table row wise in c#

I am working on Data table in C#. I want to retrieve the data from data table row wise into an array. But i am getting exception. I want to read the data row wise.

I have tried,

        System.Data.DataTable _dtDataFile = new System.Data.DataTable();  
        myCommand.Fill(_dtDataFile);
        string[] arr1 = new string[3];
       _dtDataFile.Rows.CopyTo(arr1,0);
         Response.Write("DONE" + arr1[0]+ "<BR>" + "<BR>");

I am getting Invalid cast exception.

Can any one help how it can be done.

Thank you.

Upvotes: 2

Views: 4715

Answers (1)

Stefan
Stefan

Reputation: 14870

You are trying to copy a collection with element type DataRow (DataTable.Rows) to a string array (string[] arr1).

If you are interested in a particular (string) column on the data table, you can use the following code to extract the values:

string[] arr = _dtDataFile.Rows
  .Cast<DataRow>()
  .Select(r => Convert.ToString(r["SomeColumnName"]))
  .ToArray();

Upvotes: 3

Related Questions