使用I / O和Datagridview覆盖和保存文件

时间:2013-06-28 10:07:41

标签: c# datagridview io overwrite

Iam使用带有两个按钮的datagridview(一个用于每次保存新文件,另一个用于加载现有文件)在运行时将数据输入到datagridview并按下保存按钮创建一个新文件(这没关系)但是当我按下加载按钮并选择一个文件,编辑完成后按下保存按钮,再次创建一个新文件。但我希望覆盖该文件(将新添加的数据添加到之前保存的旧文件中)。请更正我的代码。

namespace DGVIEW_FILING
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {

                string fn = string.Format(@" {0}.txt", DateTime.Now.Ticks);
                FileStream FS = new FileStream(fn, FileMode.Create);




                // write the text from streamwriter.....
                // write the text from streamwriter.....
                TextWriter view = new StreamWriter(FS);



                int rc = dataGridView1.Rows.Count;

                for (int i = 0; i < rc - 1; i++)
                {
                    view.WriteLine(dataGridView1.Rows[i].Cells[0].Value.ToString() + "\t" +
                    dataGridView1.Rows[i].Cells[1].Value.ToString() + "\t" +
                  dataGridView1.Rows[i].Cells[2].Value.ToString());
                }



                view.Close();   // for close the fs file which created earlier......

            MessageBox.Show("DATA SAVED!! ");
        }

        private void button2_Click(object sender, EventArgs e)
        {

            DialogResult obj = new DialogResult();
            //obj = openFileDialog1.ShowDialog();
            obj= DialogResult.OK;

            // Read the text from text file....
            if ( openFileDialog1.ShowDialog() == obj ) 
            {




                TextReader done = new StreamReader(openFileDialog1.FileName );
               // FileStream fileStream = new FileStream(@" {0}.txt", FileMode.Open, FileAccess.Write);
                int row = 0;
                string line;
                while ((line = done.ReadLine()) != null)
                {
                    string[] columns = line.Split('\t');
                    dataGridView1.Rows.Add();
                    for (int i = 0; i < columns.Length; i++)
                    {
                        dataGridView1[i, row].Value = columns[i];
                    }
                    row++;


                }

                MessageBox.Show(done.ReadToEnd()); 

                done.Close();
            }




            }


        }
    }

1 个答案:

答案 0 :(得分:0)

加载时,存储文件名。 在保存时,如果已存储文件名,请改用该文件名(然后将其重置为null)。

string currentFile = null;
...
currentFile = openFileDialog1.FileName;
...
if (currentFile != null) {
    fn = currentFile;
    currentFile = null;
}