I have a settings dialog with a DataGridView, and an OK/Cancel button. When the dialog is opened, it is supplied an XML file that may or may not exist, and display the contents. Regardless of whether or not the file exists, the user must be able to modify the data in each cell in the DataGridView, along with being able to add or remove rows. When the OK button is clicked, the contents of the DataGridView must be exported to the XML file that was initially supplied.
I have been fooling around with this for several hours now, and I can't seem to get all of these requirements working at once.
Some classes that I've used include XmlDataDocument, List, DataSet, DataTable, and BindingSource.
Here is my current implementation (that fails). Something to note: I have manually set all of the Columns to ReadOnly = false. I can add new columns, but I cannot figure out how to allow deletion of columns.
public partial class DefineAuctionRulesetDialog : Form
{
private string _rulesetFile;
private DataSet _dataSet;
public DefineAuctionRulesetDialog(string rulesetFile)
{
this.Text = "Define Auction Ruleset: " + rulesetFile;
_rulesetFile = "auctions\\" + rulesetFile + ".xml";
InitializeComponent();
_dataSet = new DataSet("AuctionRuleset");
LoadRulesFromFile();
}
private void LoadRulesFromFile()
{
List<AuctionRules> rules = new List<AuctionRules>();
if (System.IO.File.Exists(_rulesetFile))
{
_dataSet.ReadXml(_rulesetFile);
}
dgvRules.DataSource = _dataSet;
//dgvRules.DataMember = "AuctionRule"; can't do this unless the file exists (the dataset needs data)
}
private void SaveRulesToFile()
{
if (dgvRules.DataSource != null)
{
_dataSet = (DataSet)(dgvRules.DataSource); //setting it to itself?
_dataSet.WriteXml(_rulesetFile);
}
}
private void btnOK_Click(object sender, EventArgs e)
{
SaveRulesToFile();
DialogResult = DialogResult.OK;
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}