tomdertech
tomdertech

Reputation: 507

DataGridView cannot add rows as "control is data-bound" after XML load

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

Answers (2)

Edper
Edper

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

Atanas Desev
Atanas Desev

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

Related Questions