Karthik
Karthik

Reputation: 2399

Store array into a data table

I have stored values retrieved from a text file into an array. Now am trying to store those array values into a data table with the below code.

The problem is that if the first row has 20 values and second row has 23 values, then 43 cells are created in data table of which last 20 (1st row column count) are empty. This continues for each row. Is there any other way to store the array into a data table?

var reader = new StreamReader(File.OpenRead(@"d:\er.txt"));
var table = new DataTable("SampleTable");

while (!reader.EndOfStream)
{
    var line = reader.ReadLine().Trim();
     var values = line.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
    string[] ee = values;
    var newRow = table.NewRow();
    for (int i = 0; i < ee.Length; i++)
    {
        table.Columns.Add();
        newRow[i] = ee[i].Trim().ToString(); // like sample [0,0]
    }
    table.Rows.Add(newRow);
}

Upvotes: 1

Views: 4170

Answers (1)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

This is because you're adding a column for each value that you add to the table. You only need to add another column if it's required. Something like the following should suffice:

var reader = new StreamReader(File.OpenRead(@"d:\er.txt"));
var table = new DataTable("SampleTable");
int columnCount = 0;
while (!reader.EndOfStream)
{
  var line = reader.ReadLine().Trim();
  var values = line.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
  string[] ee = values;
  while (columnCount < ee.Length) 
  {
    // Only add a new column if it's required.
    table.Columns.Add();
    columnCount++;
  }
  var newRow = table.NewRow();
  for (int i = 0; i < ee.Length; i++)
  {
      newRow[i] = ee[i].Trim().ToString(); // like sample [0,0]
  }
  table.Rows.Add(newRow);
}

Upvotes: 2

Related Questions