简体   繁体   中英

adding the datagridview's row to datatable

In the following code I am trying to add the selected row of datagridview to the datagridview's datasource if the selected row new row but it only adds "DataGridViewRow { Index=0 }" to the first column of the row and rest of the row is empty

    if (dataGridView1.SelectedRows[0].IsNewRow)
        {
            _dt.Rows.Add(dataGridView1.SelectedRows[0]);
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = _dt;
        }

        DataTable dtUpdated = (DataTable)dataGridView1.DataSource;
        dtUpdated.GetChanges();

        SqlCommandBuilder cb = new SqlCommandBuilder(_sqlDa);

        try
        {

            _sqlDa.Update(dtUpdated);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());

        }

As Dan mentioned above Datatable is bonded with the grid, so whenever you will add a new row or change any text in that new row automatically new row and updated values will be update to the _dt.

Still your in confusion or getting the same problem as told above then don't add 'dataGridView1.SelectedRows[0]' to the _dt.Rows because SelectedRows is a collection of object 'DataGridViewSelectedRowCollection' so better to convert the SelectedRows to Datarow or you can use another overloaded function of '_dt.Rows.Add(params Object[] values)'

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