如何将另一个文件添加到datagridview而不是覆盖
本文关键字:datagridview 覆盖 添加 另一个 文件 | 更新日期: 2023-09-27 18:07:30
我想添加另一个文件到我的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;
}
}
您正在使用System.IO.File.WriteAllText
方法,其中创建一个新的文件,将指定的字符串写入文件,然后关闭文件。如果目标文件已经存在,则将覆盖。
MSDN on WriteAllText
用File.AppendAllText(String, String)
代替这个
MSDN on AppendAllText