2013-10-28 186 views
4

我想只有一個DataGridView的選定行添加到DataTable,我使用總是從即使不選擇這一項的第一行開始的代碼...是否有人有一個想法如何解決這個請嗎?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; 
       } 
      } 

回答

9

您有權訪問SelectedRows

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

而且它的更好,如果你DataTable具有相同類型的細胞

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; 
            //^^^^^^^^^^^ 
    } 
} 
+1

謝謝哈比卜,這是非常有益的。 –

0
DataTable dt = ((DataTable)dgvQueryResult.DataSource).Clone(); 
       foreach (DataGridViewRow row in dgvQueryResult.SelectedRows) 
       { 
        dt.ImportRow(((DataTable)dgvQueryResult.DataSource).Rows[row.Index]); 
       } 
       dt.AcceptChanges();