0

在向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();
            }




            }


        }
    }
4

1 回答 1

0

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

string currentFile = null;
...
currentFile = openFileDialog1.FileName;
...
if (currentFile != null) {
    fn = currentFile;
    currentFile = null;
}
于 2013-06-28T10:21:52.087 回答