![](/img/trans.png)
[英]How do I write an external connection string config file and make my c# application recognize and read it?
[英]How do I make my DataGridView read info of a text file C#
所以我的问题是,我无法使DataGridView从已经创建的文本文件中读取信息,不知道该怎么做,我对C#还是陌生的,所以希望您能为我提供帮助:D
这是我的代码,用于保存网格中的值:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
现在,从另一种形式开始,必须用该文件中保存的值填充另一个网格。当前代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
总之,两个网格都应具有4个单元:
0设计1-Grupo 2-Valor 3-Data
而来自Form3的第二个,应该以正确的顺序读取文本文件
希望你能帮助我,谢谢。
请在下面尝试。 我已经将网格数据导出到文本文件中,其结构与如下所示在网格中的显示结构相同。
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
创建一个新的类,其属性为列名,并提供一种将导出的数据加载到类的列表集合中的方法,如下所示。在此示例中,我的网格具有两列Name和Marks。因此我在我的网格中声明了这两个属性用户类别
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { 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
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
现在在第二个表单的表单加载事件中,调用上述方法并绑定到第二个网格,如下所示
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
如果有帮助,请将其标记为答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.