簡體   English   中英

字符串數組到 C# 中的 DataGridView

[英]array of strings into a DataGridView in C#

我正在將文件的每一行讀入字符串數組:

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

每行由制表符分隔

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

我想將此字符串數組加載到 DataGridView 中。 我嘗試了以下方法:

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;

問題是所有字符串都加載到 DataGrid 的第一列:

在此處輸入圖像描述

我需要他們像這樣分開:

在此處輸入圖像描述

您將需要拆分選項卡上的行。 這是一個例子:

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

我還發現一些文檔說您需要使用 NewRow() 方法創建一個新行,然后填寫每個列的值。 這就是它的樣子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM