简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM