by WebSurfer
2019年4月26日 12:14
XML ファイルからデータを取得して Windows Forms アプリの DataGridView に表示し、それをユーザーが編集して結果を XML ファイルに書き戻すサンプルを書きます。
ASP.NET Web Forms アプリの場合は先の記事「XML ファイルの更新操作」に書きましたのでそちらを見てください。
アプリの基本的な構成は、DataGridView ⇔ BindingSource ⇔ DataSet ⇔ XML ファイルとしています。
DataSet.ReadXml メソッドで XML ファイルからデータを DataSet に読み込み、BindingSource 経由で DataGridView に表示。ユーザーが DataGridView に表示されたデータを編集後(編集結果は DataSet に反映されます)、ボタンクリックで DataSet.WriteXml メソッドにより編集結果を XML ファイルに書き戻すという操作を行います。
Windows Forms アプリの場合、ASP.NET Web Froms アプリとは違って、DataSet や DataGridView などすべてのインスタンスをユーザーの PC メモリ上に保持できますので、上記の操作が可能になります。
コードは、表示・編集・更新を行うためのごく基本的な部分だけですが、以下の通りです。
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;
namespace WindowsFormsApplication1
{
public partial class Form6 : Form
{
private DataGridView dataGridView1;
private BindingSource bindingSource1;
private DataSet dataset1;
private string dir;
private string file;
public Form6()
{
InitializeComponent();
}
private void Form6_Load(object sender, EventArgs e)
{
// BindingSource をデザイナで追加すると、以下のコードは .Designer.cs
// に定義されるが、この記事のようにした場合は自力で書かないとダメ
this.components = new System.ComponentModel.Container();
this.bindingSource1 = new BindingSource(this.components);
// DataGridView と DataSet はいずれも IDisposable を継承している
// ので.Designer.cs で定義済みの Dispose(bool) メソッドで開放する
// ため以下のようにした ・・・が、ホントに必要か?
// 初期化する前に components.Add しても無効のようなので注意
this.dataGridView1 = new DataGridView();
this.dataset1 = new DataSet();
this.components.Add(this.dataGridView1);
this.components.Add(this.dataset1);
this.dataGridView1.Dock = DockStyle.Fill;
this.dataGridView1.DataSource = this.bindingSource1;
this.Controls.Add(this.dataGridView1);
this.dir = @"XML ファイルのあるフォルダ";
this.file = "XML ファイル";
this.dataset1.ReadXml(dir + file);
this.bindingSource1.DataSource = dataset1.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
this.Validate();
this.bindingSource1.EndEdit();
this.dataset1.WriteXml(dir + file,
XmlWriteMode.WriteSchema);
this.dataset1.AcceptChanges();
}
private void button2_Click(object sender, EventArgs e)
{
this.bindingSource1.RemoveCurrent();
}
}
}
XML ファイルはスキーマ付きにしています。その結果、DataTable の各列の DataType はスキーマに応じて型が設定され、例えば bool 型の場合はチェックボックスが表示されます。
DataSet.WriteXml で DELETE 操作を行うためには DataTable の当該行の DataRow.RowState プロパティを DataRowSate.Deleted に設定する必要があります。それを BindingSource.RemoveCurrent メソッドで行っています。