using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace datagrid { public partial class Form1 : Form { public Form1() { InitializeComponent(); } DataTable DTable; BindingSource SBind; //zmienne globalne private void button1_Click(object sender, EventArgs e) { DTable = new DataTable(); //nowa tebelka danych SBind = new BindingSource(); //obiekt 'komunikatora' miedzy DataTable a DataGridView SBind.DataSource = DTable; // 1st lvl connection dataGridView1.DataSource = SBind; // final connection //teraz możemy robić co chcemy z DataTable, a dataGridView będzie automatycznie aktualizowal swój stan DTable.Clear(); DTable.Columns.Add("Name"); DTable.Columns.Add("Marks"); DataRow row = DTable.NewRow(); row["Name"] = "pierwszy"; row["Marks"] = "500"; DTable.Rows.Add(row); } private void button2_Click(object sender, EventArgs e) { DTable.TableName = "Tablica danych"; //bez tego linijka niżej wyrzuci błąd! DTable.WriteXml("dane.xml"); } private void button3_Click(object sender, EventArgs e) { dataGridView1.DataSource = null; dataGridView1.AutoGenerateColumns = true; XmlReader xmlFile = XmlReader.Create("dane.xml", new XmlReaderSettings()); DataSet data = new DataSet(); data.ReadXml(xmlFile); xmlFile.Close(); DTable = data.Tables[0]; SBind = new BindingSource(); SBind.DataSource = DTable; dataGridView1.DataSource = SBind; } } }