Ошибка отображения DatagridView при подключении к файлу - PullRequest
0 голосов
/ 11 июля 2020

the GUI i am working with problem occurs while filing it is saving data amazingly and on retrieving the records on DataGridView here is the code i am trying but it is also showing the Last Value of column and 1st value of next column like this is the info in file and data from file is like: Почему одни и те же данные всегда ??

3519,laiba,99

3519,maheen,89

вот мой код:

 private void btnsave_Click(object sender, EventArgs e)
        {
            FileStream f = new FileStream("D://abc.txt", FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(f);
            sw.Write(txtregno.Text+","+txtname.Text+","+txtmarks.Text+";");
            MessageBox.Show("Saved Successfully");
            sw.Close();
        }

        private void btnshow_Click(object sender, EventArgs e)
        {
            FileStream f = new FileStream("D://abc.txt", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(f);
            string data = sr.ReadToEnd();
            string[] lineWiseRecord = data.Split(';');
            foreach (string item in lineWiseRecord)
            {
                string[] colWiseRecord = item.Split(','); 
                    dataGridView1.Rows.Add(colWiseRecord[0], colWiseRecord[1], colWiseRecord[2] );
            }
            f.Close();
            sr.Close();
        }

1 Ответ

1 голос
/ 13 июля 2020

Ваш код выдаст ошибку и не может быть запущен. Укажите количество столбцов для datagridview, а затем загрузите данные в datagirdview через foreach l oop, чтобы вы могли видеть все данные в текстовом документе. Вот мой код, вы можете попробовать следующий код, чтобы заменить его.

private void btnsave_Click(object sender, EventArgs e)
        {
            FileStream f = new FileStream("D://abc.txt", FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(f);
            sw.Write(txtregno.Text + "," + txtname.Text + "," + txtmarks.Text + ";");
            MessageBox.Show("Saved Successfully");
            sw.Close();
        }

        

        private void btnshow_Click_1(object sender, EventArgs e)
        {
            FileStream f = new FileStream("D://abc.txt", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(f);
            string data = sr.ReadToEnd();
            string[] lineWiseRecord = data.Split(';');
            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "regno";
            dataGridView1.Columns[1].Name = "Name";
            dataGridView1.Columns[2].Name = "Mark%";

            foreach (string item in lineWiseRecord)
            {
                string[] colWiseRecord = item.Split(',');
                dataGridView1.Rows.Add(colWiseRecord);
            }
            f.Close();
            sr.Close();
        }

Результат:

введите описание изображения здесь

...