0

Am new to C# and i want to know how to extract data from txt dataset and put it in c# dataset and perform some calculations with it.

This is how my dataset looks like

5.982   0.228   0.237   0.221   0.222   0.527
2.13    0.262   0.273   0.251   0.254   0.427   

Here is my amateur code:

string file = "D://test1.txt";
string tableName = "table";
string delimiter = "\t";

DataSet ds = new DataSet();
StreamReader s = new StreamReader(file);

ds.Tables.Add(tableName);

string AllData = s.ReadToEnd();

foreach (string r in rows)
{
    string[] items = r.Split(delimiter.ToCharArray());
    ds.Tables[TableName].Rows.Add(items);
}

int MaxRows = ds.Tables[0].Rows.Count;
Console.Write(MaxRows);
Console.ReadLine();

It always shows an error:

Input array is longer than the number of columns in this table.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • You have table with 0 columns defined. Define them first. – abatishchev Mar 29 '15 at 19:45
  • i want to access data only in row wise manner. only 1 column enough for me. And i have no idea how to define one column. – Alan Octavian Mar 29 '15 at 19:47
  • For instance see http://stackoverflow.com/questions/351557/how-does-one-insert-a-column-into-a-dataset-between-two-existing-columns – abatishchev Mar 29 '15 at 19:48
  • It looks like this is the second time you posted this question today. In the future, please edit your question rather than posting a new one. – BJ Myers Mar 30 '15 at 01:33

1 Answers1

1

You have to add some columns to hold the data first. Something like:

var tableName = "MyTableName";
DataTable table = ds.Tables.Add(tableName);

table.Columns.Add("firstColumnName", typeof(string));
table.Columns.Add("secondColumnName", typeof(string));
table.Columns.Add("thirdColumnName", typeof(string));
table.Columns.Add("fourthColumnName", typeof(string));
table.Columns.Add("fifthColumnName", typeof(string));
table.Columns.Add("sixthColumnName", typeof(string));

As an example of how to add rows to this table:

const string dataFilePath = @"d:\public\temp\data.txt";
string[] fileData = File.ReadAllLines(dataFilePath);
var numColumns = table.Columns.Count;

foreach (string dataItem in fileData)
{
    var items = dataItem.Split(delimiter.ToCharArray()).Take(numColumns);
    table.Rows.Add(items);
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43