Třeba takhle:
DataSet ds;
public Form1()
{
//načtení xml nebo nová instance datasetu
using (var ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
LoadDataSetFromXml(ofd.FileName);
}
else
{
InicializeDataSet();
}
}
dataGridView1.DataSource = ds.Tables["tabulka"];
}
//Inicializace datasetu s jednou tabulkou
//Tabulka má sloupce Id: Int, FirstName: string, LastName: string
private void InicializeDataSet()
{
ds = new DataSet("tabulky");
var dt = new DataTable("tabulka");
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("FirstName", typeof(string));
dt.Columns.Add("LastName", typeof(string));
ds.Tables.Add(dt);
}
//přidání záznamu
private void AddPerson(int id, string firstName, string lastName)
{
var dt = ds.Tables["tabulka"];
var r = dt.NewRow();
r["Id"] = id;
r["FirstName"] = firstName;
r["LastName"] = lastName;
dt.Rows.Add(r);
}
//odebrání záznamu
private void RemovePerson(int id, string firstName, string lastName)
{
var dt = ds.Tables["tabulka"];
foreach (DataRow r in dt.Rows)
{
if ((int)r["Id"] == id && (string)r["FirstName"] == firstName && (string)r["LastName"] == lastName)
{
dt.Rows.Remove(r);
}
}
}
//uložení tabulky
private void SaveDataSetToXml(string fileName)
{
ds.WriteXml(fileName);
}
//načtení tabulky
private void LoadDataSetFromXml(string fileName)
{
ds.ReadXml(fileName);
}
//Uložení do souboru
private void button1_Click(object sender, EventArgs e)
{
using (var sfd = new SaveFileDialog())
{
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
SaveDataSetToXml(sfd.FileName);
}
}
}
|