将文本文件数据绑定到datagrid

编程入门 行业动态 更新时间:2024-10-27 17:25:07
本文介绍了将文本文件数据绑定到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

本文发布于:2023-07-09 00:19:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1082120.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   文本文件   数据   datagrid

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!