Reputation: 507
I have populated a DataGridView from an XML file via loading to a DataSet. However, after I load the data I can no longer insert rows at run-time as I get this error:
"Rows cannot be programmatically added to the datagridview's row collection when the control is data-bound"
private void LoadBtn_Click(object sender, EventArgs e)
{
DTable.Clear();
DTable.Reset();
var ds = new DataSet();
ds.ReadXml(@"C:\setup.xml", XmlReadMode.ReadSchema);
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
DTable.Columns.Add(col.Name);
col.DataPropertyName = col.Name;
}
//dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = ds.Tables["TableName"];
}
I understand the concept of the problem I think. If my XML file only contains 7 rows and is the source of the DataGridView, then it is bound to 7 rows and more cannot be added, but I would like the user to be able to dynamically change this and then re-save the XML. I am OK with knowing how to re-save, just not how to "unlock" the row problem.
Many Thanks, Tom
Upvotes: 0
Views: 790
Reputation: 9322
Why not add to DataRow
first and then save to XML
and then re-populate DataGridView
, like:
Add to DataRow
:
DataRow dr = ds.Tables["TableName"].NewRow();
dr["FieldName1"] = value1;
dr["FieldName2"] = value2;
ds.Tables["TableName"].Rows.Add(dr);
Save to XML
:
ds.WriteXml(@"C:\setup.xml");
Re-populate DataGridView
:
dataGridView1.DataSource = ds.Tables["TableName"];
But this assumes by the way that your DataSet
named ds
(in this case) is globally declared.
Upvotes: 0
Reputation: 868
The datasource of your DataGridView is table. In that case you can add rows to the table and they will be shown in the DataGridView.
Upvotes: 0