简体   繁体   中英

Rows cannot be programmatically added to the DataGridView's rows collection

There is a little bit problem with my c# program. I have 2 DataGridViews (in 1st there are records loaded from my localhost database). When i click the A button, selected records from 1st DataGridView goes to 2nd DGV and are deleted from 1st. When i click B Button , selected records should back to 1st DGV and should be deleted from 2nd, but VS yells that rows cannot be programmatically added to the DGV.

Here is my code:

    //copy rows                 
    public void Kopiuj()
    {
        foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
        {
            object[] rowData = new object[row.Cells.Count];
            for (int i = 0; i < rowData.Length; ++i)
            {
                rowData[i] = row.Cells[i].Value;
            }

            this.dataGridView2.Rows.Add(rowData);
        }
    }


 //delete rows

    public void Usun()
    {
        foreach (DataGridViewRow selRow in dataGridView1.SelectedRows.OfType<DataGridViewRow>().ToArray())
        {
            dataGridView1.Rows.Remove(selRow);
        }
     }

//adding collumns cause it's neccesary
public void DodajKolumny()
{

    while (dataGridView2.Columns.Count < dataGridView1.Columns.Count)
    {
        foreach (DataGridViewColumn c in dataGridView1.Columns)
        {
            dataGridView2.Columns.Add(c.Clone() as DataGridViewColumn);
        }
    }


}

And now here is the code of method, which doesnt copy selected rows from DGV2 to DGV1:

public void KopiujW()
{
    foreach (DataGridViewRow row in this.dataGridView2.SelectedRows)
    {
        object[] rowData = new object[row.Cells.Count];
        for (int i = 0; i < rowData.Length; ++i)
        {
            rowData[i] = row.Cells[i].Value;

            dataGridView1.Rows.Add(rowData);
        }

        dataGridView1.Rows.Add(rowData);
    }
}

If you guys could be kind and tell me what's wrong in this code. Thx for every answer. Cheers

The grid is bound to a DataSource so it won't let you add data that way. Add the row using binding DataSource.AddNew() method in the first line of your code in the 'for' loop. Then refer to the current row of your DataGridView . The current row will be the one that your binding data source control has added. That way you can modify the data of each cell in the row.

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