Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从datagridview中选择数据并重新插入选择c_C#_Datagridview_Datasource - Fatal编程技术网

C# 从datagridview中选择数据并重新插入选择c

C# 从datagridview中选择数据并重新插入选择c,c#,datagridview,datasource,C#,Datagridview,Datasource,我试图从datagridview中选择一组行,并在单击按钮时进行更新,以便在同一视图中仅显示所选信息,以下是我当前的代码: private void btnUpdate_Click(object sender, EventArgs e) { List<DataGridViewRow> rowCollection = new List<DataGridViewRow>(); foreach (DataGridViewRow row

我试图从datagridview中选择一组行,并在单击按钮时进行更新,以便在同一视图中仅显示所选信息,以下是我当前的代码:

  private void btnUpdate_Click(object sender, EventArgs e)
    {
        List<DataGridViewRow> rowCollection = new List<DataGridViewRow>();
        foreach (DataGridViewRow row in dataGridView1.SelectedRows) {
            rowCollection.Add(dataGridView1.Rows[row.Index]); 
        }


        dataset.Tables[0].Clear();


        foreach (DataGridViewRow row in rowCollection)
        {
            DataRow r = dataset.Tables[tableName].NewRow();
            //write the data in the DataRow and then add the datarow in your datatable
            dataset.Tables[tableName].Rows.Add(r);


        }
    }

按下更新按钮后,没有错误,所选行数正确,但网格视图中没有显示任何信息,欢迎提供帮助,干杯

这里发生了几件事:

您的第二个foreach循环在每次迭代中添加一个全新的DataRow。但该行从未填充过,因此DataGridView只显示空行。 即使修复了此错误,dataset.Tables[0]仍会清除;在同一循环中使用数据之前清空数据。rowCollection中的每一行都将有空数据。 要更正此问题,我们将克隆目标DataTable。然后,我们将使用DataRowCollection.Addparams对象[]值而不是DataRowCollection.AddDataRow行,将rowCollection中的每一行添加到克隆表中。之后,我们将清除目标表并将克隆合并回其中

private void btnUpdate_Click(object sender, EventArgs e)
{
    List<DataGridViewRow> rowCollection = new List<DataGridViewRow>();

    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {
        // Adds the selected rows in order from most recently selected to first selected.
        rowCollection.Add(dataGridView1.Rows[row.Index]);

        // Adds the selected rows in order from first selected to most recently selected.
        //rowCollection.Insert(0, dataGridView1.Rows[row.Index]);
    }

    DataTable clone = this.DataSet.Tables[0].Clone();

    foreach (DataGridViewRow row in rowCollection)
    {
        object[] values = new object[row.Cells.Count];

        for (int i = 0; i < row.Cells.Count; i++)
        {
            values[i] = row.Cells[i].Value;
        }

        clone.Rows.Add(values);
    }

    this.DataSet.Tables[0].Clear();
    this.DataSet.Tables[0].Merge(clone);
}