如何将另一个文件添加到datagridview而不是覆盖

时间:2015-08-11 12:41:52

标签: c# datagridview linq-to-xml

我想将另一个文件添加到datagridview而不是覆盖它。当我打开另一个文件时,我希望使用旧文件和我在datagridview中打开的新文件。 这是我到目前为止打开新文件。

private void importButton_Click(object sender, EventArgs e)
        {
            ImportNewFile();

        }
private void ImportNewFile()
        {
            //Opens Window, where you selecting file to load
            OpenFileDialog ofd = new OpenFileDialog();
            dataGridView1.MultiSelect = true;
            ofd.Multiselect = true;         
            System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                oldfilePath = filePath; // Saving old path data
                userSelectedFilePath = ofd.FileName;
                var content = File.ReadAllText(ofd.FileName);
                checkedListBox1.Items.Clear();

                    try
                    {
                        this.DocumentXml = XDocument.Parse(content);
                        content = File.ReadAllText(filePath);
                        System.IO.File.WriteAllText(@"filePath.txt", userSelectedFilePath);
                        filePath = userSelectedFilePath;


                    }

                    catch
                    {
                        filePath = oldfilePath; // If your file is wrong, it back to previous data
                        content = File.ReadAllText(filePath);
                        System.IO.File.WriteAllText(@"filePath.txt", filePath);
                        MessageBox.Show("Its not a .xml file, or code is wrong", "Wrong File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    var groups = this.DocumentXml.Root.Elements("group");

                    foreach (var group in groups)
                    {
                        checkedListBox1.Items.Add(group.Attribute("name").Value); // Adding Items to checkedItemBox1
                    }
                    // Adding data from your DNSFile to dataGridView1
                    hostsDataSet.Clear();
                    hostsDataSet.ReadXml(filePath);
                    dataGridView1.DataSource = hostsDataSet;
                    dataGridView1.DataMember = "item";


            }
        }
        public string userSelectedFilePathImport
        {
            get
            {
                return tbFilePath.Text;
            }
            set
            {
                tbFilePath.Text = value;
            }
        }

1 个答案:

答案 0 :(得分:0)

您正在使用{strong}创建新文件的System.IO.File.WriteAllText方法,将指定的字符串写入文件,然后关闭该文件。如果目标文件已存在,则覆盖

MSDN on WriteAllText

使用File.AppendAllText(String, String)代替此!

MSDN on AppendAllText