【问题标题】:DataGridView selected rows to DataTableDataGridView 选择的行到 DataTable
【发布时间】:2013-11-07 12:16:17
【问题描述】:

我正在尝试仅将 DataGridView 的选定行添加到 DataTable 中,我使用的代码始终从第一行开始,即使未选择此行...有人知道如何请解决这个问题?

 DataTable dt = new DataTable("Rapport");

            //Generating columns to datatable:
            foreach (DataGridViewColumn column in dataGridView1.Columns)
                dt.Columns.Add(column.Name, typeof(string));

            //Adding selected rows of DGV to DataTable:
            for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
            {
                dt.Rows.Add();
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    dt.Rows[i][j] = dataGridView1[j, i].Value;
                }
            }

【问题讨论】:

    标签: c# winforms datagridview datatable selection


    【解决方案1】:
    DataTable dt = ((DataTable)dgvQueryResult.DataSource).Clone();
    foreach (DataGridViewRow row in dgvQueryResult.SelectedRows)
    {
        dt.ImportRow(((DataTable)dgvQueryResult.DataSource).Rows[row.Index]);
    }
    dt.AcceptChanges();
    

    【讨论】:

      【解决方案2】:

      你必须访问SelectedRowslike

      dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;
      

      如果您的DataTable 与 Cell 的类型相同,那就更好了

      DataTable dt = new DataTable();
       foreach (DataGridViewColumn column in dataGridView1.Columns)
          dt.Columns.Add(column.Name, column.CellType); //better to have cell type
      

      所以你的代码是:

      DataTable dt = new DataTable();
      foreach (DataGridViewColumn column in dataGridView1.Columns)
          dt.Columns.Add(column.Name, column.CellType); //better to have cell type
      for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
      {
           dt.Rows.Add();
           for (int j = 0; j < dataGridView1.Columns.Count; j++)
           {
               dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;
                                         //^^^^^^^^^^^
           }
       }
      

      【讨论】:

      • 谢谢 Habib,这很有帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2017-01-10
      • 2016-07-29
      相关资源
      最近更新 更多