0

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

tomdertech
  • 497
  • 1
  • 9
  • 27
  • How are you trying to insert a row that gives you that error? – sr28 Aug 07 '14 at 11:44
  • I am highlighting the row on the DGV and using this code through a button click dataGridView1.Rows.Insert(dataGridView1.CurrentRow.Index);: – tomdertech Aug 07 '14 at 12:00
  • This may help: http://stackoverflow.com/questions/4328769/adding-rows-programatically-to-a-datagridview-that-is-data-bound – sr28 Aug 07 '14 at 14:04

2 Answers2

0

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.

Atanas Desev
  • 858
  • 5
  • 13
0

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.

Edper
  • 9,144
  • 1
  • 27
  • 46
  • "Why not add to DataRow first and then save to XML and then re-populate DataGridView" because the user may want to keep adding and saving, then add somemore ... – tomdertech Aug 07 '14 at 12:20
  • Do not let then the user add to a `DataGridView` directly but to `Textbox(es)` for example and then do the code above. In that case they could add as much as they want. – Edper Aug 07 '14 at 12:23
  • This would not be flexible enough ... No point in using the power of a DGV and then being limited by finite textbox(es) – tomdertech Aug 07 '14 at 13:28