【转】从TXT导入到dataGridView

代码
public bool TextToDgv(string path) // 这个函数那里出错了?
{
System.Data.DataTable table1
= new System.Data.DataTable();//定义数据存放的表
StreamReader reader = new StreamReader(path,Encoding.Default);
string[] cols;
string[] row;
string tempdata;

tempdata
=(string) reader.ReadLine();
tempdata
= tempdata.Trim();
if (tempdata == "")
{
MessageBox.Show(
"没东西啊");
return false;
}
cols
= tempdata.Split('\x20');
for (int i = 0; i < cols.Length; i++)//添加列头
{
table1.Columns.Add(cols[i],
typeof(string));
}

try
{
while (reader.Peek() != -1) //添加行
{
System.Data.DataRow datarw
= table1.NewRow();
tempdata
= reader.ReadLine();
tempdata
= tempdata.Trim();
row
= tempdata.Split('\x20');
for (int i = 0; i < table1.Columns.Count; i++)
{
datarw[i]
= row[i];
}
table1.Rows.Add(datarw);
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
dataGridView.DataSource
= table1;//将表与dataGridView绑定
return true;
}
原文地址:https://www.cnblogs.com/gebenhagen/p/1708807.html