C# 从 .txt 文件中读取,然后将数据导出到 DataGridView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16498614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading from .txt file, then exporting data to DataGridView
提问by Placeholder
I know this is a laughable question, but God, I've spent my entire last day banging my head with it and it just won't work! The goddamn teacher didn't even mention anything about importing any data into DataGridView!
我知道这是一个可笑的问题,但是上帝啊,我最后一天都在用它来敲打我的头,但它根本行不通!该死的老师甚至没有提到将任何数据导入DataGridView!
I have a C# Windows Forms homework assignment: I have to read data from a .txt(users) file and paste it into a DataGridViewtable in C# Microsoft Visual Studio 2012. The data in the users.txtfile is something like that with TAB delimiters:
我有一个 C# Windows 窗体作业:我必须从.txt(用户)文件中读取数据并将其粘贴到C# Microsoft Visual Studio 2012 中的DataGridView表中。users.txt文件中的数据类似于带有 TAB 分隔符的数据:
-------------------------------------------------
ID Name Surname Telephone VIP Age Balance
-------------------------------------------------
0001 John Killer 1-500-300 0 13 2272
0002 Name Surname 1-500-200 0 27 225
0003 Martin King 1-500-400 1 41 1070
Ignore the label names (ID, Name, Surname...), I wrote them only for clarity, the real file has only the raw user data in it.
忽略标签名称(ID、Name、Surname...),我写它们只是为了清楚起见,真实文件中只有原始用户数据。
Now, I have previously created a class Users, which has these fields:
现在,我之前创建了一个 class Users,其中包含以下字段:
- ID
- Name
- Surname
- Telephone
- VIP
- Bought items
- Price
- ID
- 姓名
- 姓
- 电话
- 贵宾
- 购买物品
- 价钱
and then created a DataGridView (usersDataGridView) and imported the fields from class Usersin it.
然后创建了一个 DataGridView ( usersDataGridView) 并从其中导入了类Users中的字段。
OK, algorithmically this is somewhat easy task, ain't it?
好的,从算法上来说,这是一个有点简单的任务,不是吗?
My idea was doing the following: reading the file content with a StreamReader, saving each line to a string, then splitting the string into parts using \tas a delimiter with String.Split.
我的想法是做如下:读取一个文件的内容StreamReader,保存每行一个字符串,然后分割字符串转换成使用部分\t作为一个分隔符String.Split。
However, once I got those lines split... well, I basically have no idea how to import them into the DataGridView (I "know" it should be as a DataSourcebut... the Visual Studio 2012's UI seems way too "complicated" for me to let me figure out how I can point a string or whatever goddamn data type it is as a DataSource).
但是,一旦我将这些行拆分...好吧,我基本上不知道如何将它们导入 DataGridView(我“知道”它应该是一个DataSource但是...Visual Studio 2012 的 UI 似乎太“复杂”了让我弄清楚如何将字符串或任何该死的数据类型作为数据源)。
My pitiful attempts had led me to the following:
我可怜的尝试使我得出以下结论:
Attempt 1:
尝试 1:
public void Test_1()
{
string filePath = string.Format("{0}/databases/{1}", AppDomain.CurrentDomain.BaseDirectory, "user_db.txt");
string[] textData = System.IO.File.ReadAllLines(filePath);
string[] headers = textData[0].Split('\t');
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('\t'));
//Set the DataSource of DataGridView to the DataTable
promotionsDataGridView.DataSource = dataTable1;
}
Attempt 2:
尝试 2:
public void ReadFromFile()
{
string delimeter = "\t";
string tableName = "BooksTable";
string fileName = string.Format("{0}/databases/{1}", AppDomain.CurrentDomain.BaseDirectory, "bigtest.sql");
DataSet dataset = new DataSet();
StreamReader sr = new StreamReader(fileName);
dataset.Tables.Add(tableName);
dataset.Tables[tableName].Columns.Add("InventoryID");
dataset.Tables[tableName].Columns.Add("Brand");
dataset.Tables[tableName].Columns.Add("Category");
dataset.Tables[tableName].Columns.Add("Description");
dataset.Tables[tableName].Columns.Add("Promotions");
dataset.Tables[tableName].Columns.Add("Quantity");
dataset.Tables[tableName].Columns.Add("Price");
string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(delimeter.ToCharArray());
dataset.Tables[tableName].Rows.Add(items);
}
this.productsDataGridView.DataSource = dataset.Tables[0].DefaultView;
}
However I keep getting some bullshit error like
但是我不断收到一些废话错误,例如
Input array size is bigger than the whatever
输入数组大小大于任何
Since I have literally no experience with DataGridViewI guess I have some terrible mistakes at algorhitmic level, right?!
由于我几乎没有任何经验,DataGridView我想我在算法级别上有一些可怕的错误,对吧?!
Please, anyone, help me! I have read, copied, pasted, compiled and debugged from like 20 different issues on similar topic and I am still at nowhere!
请任何人帮助我!我已经阅读、复制、粘贴、编译和调试了大约 20 个关于类似主题的不同问题,但我仍然无处可去!
What's the properway of reading data from a .txtfile, then pasting it to a DataGridView?
从文件中读取数据然后将其粘贴到 DataGridView的正确方法是什么.txt?
Any help or answers are deeply appreciated!!
任何帮助或答案深表感谢!!
采纳答案by Alaa Masoud
If you already have a User object defined you can add a static method to it that loads the data to a list of users and bind it to the grid view.
如果您已经定义了一个 User 对象,您可以向它添加一个静态方法,将数据加载到用户列表并将其绑定到网格视图。
public class User {
public string Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Telephone { get; set; }
public bool Vip { get; set; }
public int Age { get; set; }
public decimal Balance { get; set; }
public static List<User> LoadUserListFromFile(string path) {
var users = new List<User>();
foreach (var line in File.ReadAllLines(path)) {
var columns = line.Split('\t');
users.Add(new User {
Id = columns[0],
Name = columns[1],
Surname = columns[2],
Telephone = columns[3],
Vip = columns[4] == "1",
Age = Convert.ToInt32(columns[5]),
Balance = Convert.ToDecimal(columns[6])
});
}
return users;
}
}
Then you can simply load that into a data grid:
然后您可以简单地将其加载到数据网格中:
usersDataGridView.DataSource = User.LoadUserListFromFile("user_db.txt");

