【转】从TXT导入到dataGridView

本文介绍了一个C#函数,用于将文本文件的内容转换并显示在一个DataGridView中。该函数首先读取指定路径下的文本文件,并将其内容解析为表格形式,然后将这些数据加载到DataGridView组件中进行展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ContractedBlock.gifExpandedBlockStart.gif代码
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/archive/2010/04/10/1708807.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值