问题描述
我有一个问题,在单击按钮时,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();
}
解决方法
试试下面的代码将网格数据写入文件。代码只是将每个单元格写入文件,然后写入一个 Bar “|”分隔符,除非该单元格是该行的最后一个单元格。我们不希望行尾有分隔符。
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();
}
}
}
}
然后在读取文件的代码中......
DataTable tabela;
private void ucitaj() {
//DataTable tabela = new DataTable();
tabela.Rows.Clear();
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);
}
dataGridView1.DataSource = tabela;
}
AND... 您需要将 DataTable
... tabela
移动为全局变量。所以让 tabela
全球化...
DataTable tabela;
然后在 Load
事件中,更改行...
DataTable tabela = new DataTable();
到...
tabela = new DataTable();