简体   繁体   English

将datagridview的行添加到datatable

[英]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 在下面的代码中,如果所选的行是新行,但我尝试将所选的datagridview的行添加到datagridview的数据源中,但仅将“ DataGridViewRow {Index = 0}”添加到该行的第一列,而其余行为空

    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. 如上文Dan所述,Datatable与网格绑定,因此,每当您添加新行或更改该新行中的任何文本时,都会自动将新行和更新后的值更新为_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)' 仍然很困惑或遇到与上述相同的问题,然后不要将_dataGridView1.SelectedRows [0]添加到_dt.Rows中,因为SelectedRows是对象“ DataGridViewSelectedRowCollection”的集合,因此最好将SelectedRows转换为Datarow或您可以使用另一个重载函数'_dt.​​Rows.Add(params Object [] values)'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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