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);
}
4
  • tables are rectangular by nature; what do you want to do here? what would "success" look like? Commented Dec 5, 2011 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. Commented Dec 5, 2011 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 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. Commented Dec 5, 2011 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 Commented Dec 5, 2011 at 12:55

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.