1

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

1
  • You need to split each line by that delimiter, and then add each of those split values to each column for each row, instead of dt.Rows.Add(s); Commented Jun 21, 2022 at 19:28

1 Answer 1

2

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);
}
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.