Home > Back-end >  array of strings into a DataGridView in C#
array of strings into a DataGridView in C#

Time:06-22

I'm reading each line of a file into an array of strings:

string[] lines = File.ReadAllLines(filePath);

Each line is separated by a tab

lines[0] = "John\tPizza\tRed\tApple"

I want to load this string array into a DataGridView. I tried the following:

DataTable dt = new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Food",typeof(string));
dt.Columns.Add("Color",typeof(string));
dt.Columns.Add("Fruit",typeof(string));

foreach(string s in lines)
{
   dt.Rows.Add(s);
}

myDataGridView.DataSource = dt;

The problem is that all the strings are loaded to the first column of the DataGrid:

enter image description here

I need them to be separated like this:

enter image description here

CodePudding user response:

You will need to split the lines on the tab. Here is an example:

foreach (string s in lines)
{
   var splitLine = s.Split("\t");
   dt.Rows.Add(splitLine);
}

I also found some documentation that says you need to create a new row with the NewRow() method and then fill out each column value. Here is what that would look like:

foreach (string s in lines)
{
   // Split the line
   var splitLine = s.Split("\t");

   // Create the new row
   var newRow = dt.NewRow();
   newRow["Name"] = splitLine[0];
   newRow["Food"] = splitLine[1];
   newRow["Color"] = splitLine[2];
   newRow["Fruit"] = splitLine[3];

   // Add the row to the table
   dt.Rows.Add(newRow);
}
  • Related