【问题标题】:Selecting Data from datagridview and re-inserting selection c#从datagridview中选择数据并重新插入选择c#
【发布时间】:2015-07-12 06:35:11
【问题描述】:

我正在尝试从 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);


        }
    }

按下更新按钮后没有错误并且选择的行数是正确的,但网格视图中没有显示任何信息,感谢任何帮助,干杯!

【问题讨论】:

    标签: c# datagridview datasource


    【解决方案1】:

    这里发生了几件事:

    1. 您的第二个foreach 循环每次迭代都会添加一个全新的DataRow。但该行从未填充 - 因此DataGridView 仅显示空行。
    2. 即使您修复了此错误,dataset.Tables[0].Clear(); 也会先清空数据,然后您才能在同一循环中使用它。 rowCollection 中的每一行都会有 null 数据。

    为了纠正这个问题,我们将克隆目标 DataTable。然后我们将使用DataRowCollection.Add(params object[] values) 而不是DataRowCollection.Add(DataRow row)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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2018-02-25
      • 2015-09-22
      • 1970-01-01
      • 2011-05-17
      • 2014-12-31
      相关资源
      最近更新 更多