-1

How to convert one dimensional Array to the DataTable?

For Example: we have following multiple Arrays with different lengths and want to convert to Datatable.

DataTable dt = new DataTable();
dt.Columns.Add("FirstName");
dt.Columns.Add("MiddelName");
dt.Columns.Add("LastName");
dt.Columns.Add("City");
dt.Columns.Add("State");
dt.Columns.Add("Zip");

string[] strArray = "naveen, kumar, katara, , CA, 92606".Split(Char.Parse(","));
string[] strArray1 = "Aadhya, , Adtya, Irvine, CA, 98623".Split(Char.Parse(","));
string[] strArray2 = "xyz, , mno".Split(Char.Parse(","));

var convertedTable = GetDataTable(strArray, dt);
convertedTable = GetDataTable(strArray1, dt);

//Final output as Converted table:
convertedTable = GetDataTable(strArray2, dt);
Ian
  • 30,182
  • 19
  • 69
  • 107
  • possible duplicate of [How to create a DataTable in C# and how to add rows?](http://stackoverflow.com/questions/1042618/how-to-create-a-datatable-in-c-sharp-and-how-to-add-rows) – MethodMan Aug 25 '15 at 20:41
  • there is an easier way to do this but doing it I can post you an example of how to do this however in my opinion I think that you should be using a `List` to initialize your row data.. please let me know if you would like to see an example on how to do this.. – MethodMan Aug 25 '15 at 21:40

1 Answers1

0

you could manually add the rows

        dt.Rows.Add(strArray[0], strArray[1], strArray[2], strArray[3], strArray[4], strArray[5]);
        dt.Rows.Add(strArray1[0], strArray1[1], strArray1[2], strArray1[3], strArray1[4], strArray1[5]);
        dt.Rows.Add(strArray2[0], strArray2[1]);

        dataGridView1.DataSource = dt;