如何在C#中从文件.txt中填充dataGridView的分割空间 [英] How split space to fill dataGridView from file .txt in C#

查看:95
本文介绍了如何在C#中从文件.txt中填充dataGridView的分割空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我需要帮助:-)



i有file.txt,内容如下:



00001 JhonKey 023301923
$ b $ 00 00002 Hercules 023039910



i希望通过datatable将此文件加载到datagridview,结果在datagrid中下面:



COL1 | COL2 | COL3

-----------------------------------

00001 | JhonKey | 023301923

00002 |赫拉克勒斯| 023039910



我试试这段代码:



 使用(StreamReader SR =  new  StreamReader(txtFileName))
{
int row = 0 ;
string 行;
while ((line = SR.ReadLine())!= null
{
string [] Columns = line.Split(' );
dataGridView2.Rows.Add();
for int i = 0 ; i < Columns.Length; i ++)
{
dataGridView2 [i,row] .Value = Columns [i];
}
row ++;
}
}



但结果不如预期,这个错误如下:



COL1 | COL2 | COL3

----------------------------------------- ---------------

00001 JhonKey 023301923 | |

00002 Hercules 023039910 | |

解决方案

错误是这一行:



  string  [] Columns = line.Split(' ,'); 





为什么要用逗号分隔而不是空白?你的字符串看起来像00001 JhonKey 023301923而不是00001,JhonKey,023301923:



  string  [] Columns = line.Split(' '); 


hi to all, i need to help :-)

i have file.txt with content like below :

00001 JhonKey 023301923
00002 Hercules 023039910

i want load this file to datagridview through datatable, and the result in datagrid like below :

COL1 | COL2 | COL3
-----------------------------------
00001 | JhonKey | 023301923
00002 | Hercules | 023039910

i'm try this code :

using (StreamReader SR = new StreamReader(txtFileName)) 
            {
                int row = 0;
                string line;
                while ((line = SR.ReadLine())!= null)
                {
                    string[] Columns = line.Split(',');
                    dataGridView2.Rows.Add();
                    for (int i = 0; i < Columns.Length; i++)
                    {
                        dataGridView2[i, row].Value = Columns[i];
                    }
                    row++;
                }
            }


but the result not as expected, this wrong like below :

COL1 | COL2 | COL3
--------------------------------------------------------
00001 JhonKey 023301923 | |
00002 Hercules 023039910 | |

解决方案

The error is this row:

string[] Columns = line.Split(',');



Why do you split on comma instead of blank? Your string looks like "00001 JhonKey 023301923" and not "00001,JhonKey,023301923":

string[] Columns = line.Split(' ');


这篇关于如何在C#中从文件.txt中填充dataGridView的分割空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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