【发布时间】:2021-07-12 22:21:04
【问题描述】:
我有一个问题,点击按钮时,dataview 应该从文本文件中获取所有数据。 我不明白为什么它不起作用。 我有另一个功能可以将数据放入文本文件中,该功能有效。 任何人都可以帮助我吗? 提前致谢 This is code of the function which should get all data and put them into the dataviewgrid when I run the program, but there is some problem , I dont get error messages at all , but its not happening . This is code which works really good , it showing all columns and all data will be in text file filling data data which I got in txt file
private void dodajToolStripMenuItem_Click(object sender, EventArgs e) {
//upis u datoteku
using (TextWriter smesti = new StreamWriter("podaci.txt")) {
for (int i = 0; i < dataGridView1.Rows.Count; i++) {
if (!dataGridView1.Rows[i].IsNewRow) {
for (int j = 0; j < dataGridView1.Columns.Count; j++) {
smesti.Write(dataGridView1.Rows[i].Cells[j].Value.ToString());
if (j < dataGridView1.Columns.Count - 1) {
smesti.Write("|");
}
}
smesti.WriteLine();
}
}
} }
private void Admin_Load(object sender, EventArgs e)
{
DataTable tabela = new DataTable();
tabela.Columns.Add("ID", typeof(int));
tabela.Columns.Add("Naziv", typeof(string));
tabela.Columns.Add("Zanr", typeof(string));
tabela.Columns.Add("Duzina", typeof(int));
tabela.Columns.Add("Granica godina: ", typeof(int));
dataGridView1.DataSource = tabela;
}
private void ucitaj()
{
DataTable tabela = new DataTable();
string[] tekst = File.ReadAllLines("podaci.txt");
string[] vrednosti;
for (int i = 0; i < tekst.Length; i++)
{
vrednosti = tekst[i].ToString().Split('|');
string[] red = new string[vrednosti.Length];
for (int j = 0; j < vrednosti.Length; j++)
{
red[j] = vrednosti[j].Trim();
}
tabela.Rows.Add(red);
}
}
private void button1_Click(object sender, EventArgs e)
{
ucitaj();
}
【问题讨论】:
-
还有一件事,我如何设置 ID 列的主键? :)
-
请编辑您的问题以显示您的实际代码,而不是它的图像
-
好的,我添加了代码
-
代码使用
Tab和“|”写入文件有什么原因吗(Bar) 字符作为每个字段的分隔符+"\t"+"|",然后,当代码读取文件时,它似乎在“/”正斜杠字符上分割字段....Split('/');?这显然行不通。此外,在编写文件时,代码从不将每一“行”放在单独的行上。这将在文本文件中创建一 (1) 行数据。因此,您将不知道哪些数据进入了哪一行。你能澄清一下吗? -
那个“|”仅用于组织更好的数据。
标签: c# datagridview dataview