2

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.

Patan
  • 17,073
  • 36
  • 124
  • 198
  • 1
    I think these posts have the answer you're searching for: http://stackoverflow.com/questions/3573618/c-datatable-to-arraylist and http://stackoverflow.com/questions/3910815/from-datatable-to-array-no-loop – Marco Apr 10 '12 at 11:28
  • 1
    use datareader instead of dataset – Imran Rizvi Apr 10 '12 at 11:36

1 Answers1

3

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();
Stefan
  • 14,530
  • 4
  • 55
  • 62
  • 1
    Tanky you.Its reading data column wise. Can you modify that I will get all data of a single row into an array. This need to be done for all rows as loop. – Patan Apr 10 '12 at 11:54