将文本文件数据绑定到datagrid [英] Bind text file data to datagrid

查看:78
本文介绍了将文本文件数据绑定到datagrid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



请告诉我如何将文本文件数据绑定到c#windows应用程序中的数据网格。



下面是我试过的代码,但它执行没有错误但没有给出任何结果

Hi all

Please tell me how to bind text file data to a datagrid in c# windows application.

below is the code i tried but its executing without error but not giving any result

DataGridView dataGridView1 = new DataGridView();
dataGridView1.Dock = DockStyle.Fill;

//Read the data from text file
string[] textData = System.IO.File.ReadAllLines(@"D:\\Display.txt");
string[] headers = textData[0].Split(',');

//Create and populate DataTable
DataTable dataTable1 = new DataTable();
foreach (string header in headers)
 dataTable1.Columns.Add(header, typeof(string), null);
for (int i = 0; i < textData.Length; i++)
 dataTable1.Rows.Add(textData[i]);

//Set the DataSource of DataGridView to the DataTable
dataGridView1.DataSource = dataTable1;



请告诉我是什么问题或任何其他解决方案。


Please tell me what is the problem or any other solution.

推荐答案

您需要将新创建的dataGridView1添加到表单中。

You need to add newly create dataGridView1 to your form.
dataGridView1.DataSource = dataTable1;
this.Controls.Add(dataGridView1);





我不确定你的文本文件数据是如何排列的,但看起来你做错了。例如,如果您有如下文本文件



I'm not sure how your text file data arranged, but it seems you are doing it wrong way. for example if you have text file like below

Column1,Column2
data11,data12
data21,data22



然后你的代码应该如下


then your code should be like below

DataTable dataTable1 = new DataTable();
foreach (string header in headers)
    dataTable1.Columns.Add(header, typeof(string), null);
for (int i = 1; i < textData.Length; i++)
    dataTable1.Rows.Add(textData[i].Split(','));



1.请注意,添加数据已开始来自索引1(第二行)

2.添加行数据时,您可以拆分并设置每列的值,否则行内容将仅分配给第一列。


1. note that, adding data started from index 1 (second row)
2. when adding row data you can split and set values for each column, otherwise line content will assign to first column only.


这篇关于将文本文件数据绑定到datagrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆