Home > OS >  populate datatable with arrays of strings
populate datatable with arrays of strings

Time:05-31

How do i populate this dataTable with array of strings? Im using this template but i can only add data hardcoded... I have an string[]values which contains my data and that should be added to the datatable. I think its quite easy but i don't see it. i've been trying to loop through it but that doens't seem to work? Think im missing a crucial step. I've created a my datatable here :

 DataTable dt = new DataTable() { TableName = "MBR" };

Adding the columns to it

string[] columns = new string [l];

        for (int i = 0; i < l; i  )
        {
            columns[i] = tags[i];
        }

        for (int i = 0; i < timeStamps.Count(); i  )
        {
            foreach (var item in tagCollection)
            {
                if (timeStamps[i].Date == item.time)
                {
                    Console.WriteLine(item.time   " "   item.name );
                }
            }
        }
  dt.Columns.AddRange(columns.Select(c => new DataColumn(c.ToString())).ToArray());

And this i used in the template my collegue is working with and we need to provide the data here

   var rows = new string[][]
             {
                 new string[] {"1", "2", "false" },
                 new string[] { "test", "10000", "19.9" },
              };
 foreach (var row in rows)
            {
                dt.Rows.Add(row);
            }

            //Convert datatable to dataset and add it to the workbook as worksheet
            ds.Tables.Add(dt);
            workbook.Worksheets.Add(ds);

I've got many columns like 500 . And i need to add to each column a piece of data which i get from my string[]. which can contains 10 or 500 records it depends. I need to add each record to a row. My columns are already working in this thing. I just need a way to add multiple Arrays to the table

CodePudding user response:

This works for me:

DataTable dt = new DataTable() { TableName = "MBR" };

dt.Columns.Add(new DataColumn("A", typeof(string)));
dt.Columns.Add(new DataColumn("B", typeof(string)));
dt.Columns.Add(new DataColumn("C", typeof(string)));

var rows = new string[][]
{
    new string[] {"1", "2", "false" },
    new string[] { "test", "10000", "19.9" },
};

foreach (var row in rows)
{
    dt.Rows.Add(row);
}

That gives me:

DataTable

CodePudding user response:

Here's how you might fill a datatable from a file of people:

var people = new DataTable();
people.Columns.Add("Name");//string
people.Columns.Add("Age", typeof(int));
people.Columns.Add("HireDate", typeof(DateTime));
people.Columns.Add("IsManager", typeof(bool));

foreach(var line in File.ReadLines("people.csv")){
  var bits = line.Split(',');
  dt.Rows.Add(new object[]{ 
    bits[0], //Name
    int.Parse(bits[1]), //Age
    DateTime.Parse(bits[2]), //HireDate
    bool.Parse(bits[3]) //IsManager
  });
}

It would, of course, be preferable to use some library like Csvhelper if you're reading from a CSV - it can read into DataTables directly and is a lot more sophisticated than this example. This is just to show the process of "make a datatable, add columns, add rows by providing values for columns"

It would be better to create a strongly typed datatable for this:

  • Add a new DataSet type of file to your project and goive it a good name
  • Open it, right click the surface, choose Add DataTable, give it a sensible name
  • Right click the table, choose Add Column .. add a column and set its name, data type, default value etc...
  • Repeat until all columns are done

Using this in your code is mostly the same as above, except you make an instance of the table. It is an inner class so you create it using the name of the dataset too:

var dt = new YourDataSetNameHere.YourDataTableNameHere_DataTable();

//the columns are already added, you don't need to add them

foreach(var line in ...){
  ...

  dt.Add_YourDataTableNameHere_Row(
    bits[0], //Name
    int.Parse(bits[1]), //Age
    DateTime.Parse(bits[2]), //HireDate
    bool.Parse(bits[3]) //IsManager
  );
}

They're a lot nicer to use than regular weakly typed datatables

  •  Tags:  
  • c#
  • Related