1

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);
}
mindless.panda
  • 4,014
  • 4
  • 35
  • 57
Karthik
  • 2,391
  • 6
  • 34
  • 65
  • tables are rectangular by nature; what do you *want* to do here? what would "success" look like? – Marc Gravell Dec 05 '11 at 12:53
  • show your output table structure to clear that what are you trying to do.. you can't do as you expecting to do with DataTable. – Niranjan Singh Dec 05 '11 at 12:53
  • The file is delimited, consider going straight to a data table using FileHelpers.Net - it will eliminate any parsing you have to do. See http://stackoverflow.com/questions/1898/csv-file-imports-in-net for one type of usage. You can use any delimiter you want, not just a comma. – dash Dec 05 '11 at 12:54
  • @MarcGravell each row may have different columns so i need to create columns in data table dynamically for example 1st row may have 20 columns and second row may have 23..i need to create a data table from array values – Karthik Dec 05 '11 at 12:55

1 Answers1

2

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);
}
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114