2015-05-03 188 views
0

enter image description here如何將整個列從一個datagridview複製到另一個?

有兩個datagridview(dgvReport和dgvReport2)。選擇字段後,dgvReport顯示來自服務器的數據(工作正常)。

複選框是dgvReport中列的名稱。例如,如果用戶選擇「電子郵件」,例如應該將「電子郵件」的列和其行數據添加到dgvReport2。

我的問題是,當我選擇多個複選框時,行的輸出只顯示在dgvReport2的第一列而不是在適當的列下。例如,在屏幕截圖中,列「fname」數據顯示在dgvReport2的電子郵件列下。

如何將行數據放在適當的列下?

下面是我的編碼:

'Add dynamic column 
Dim newCol As Integer = 0 

If chkEmail.Checked = True Then 
    Dim column As New DataGridViewTextBoxColumn 
    dgvReport2.Columns.Insert(newCol, column) 

    With column 
     .HeaderText = "email" 
     .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells 
     .ReadOnly = True 
    End With 

    For rows As Integer = 0 To dgvReport.Rows.Count - 1 
     For colcnt As Integer = 0 To dgvReport.Columns.Count - 17 
      dgvReport2.Rows.Add(dgvReport.Rows(rows).Cells(0).Value) 
     Next 
    Next 

    newCol += 1 
End If 

If chkFname.Checked = True Then 
    Dim column As New DataGridViewTextBoxColumn 
    dgvReport2.Columns.Insert(newCol, column) 

    With column 
     .HeaderText = "fname" 
     .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells 
     .ReadOnly = True 
    End With 

    For rows As Integer = 0 To dgvReport.Rows.Count - 1 
     For colcnt As Integer = 0 To dgvReport.Columns.Count - 17 
      dgvReport2.Rows.Add(dgvReport.Rows(rows).Cells(1).Value) 
     Next 
    Next 
    newCol += 1 
End If 

回答

0

我發現我自己的問題的答案。希望充分它將幫助別人誰是尋找同一個問題:

 If dgvReport2.Rows.Count > 0 Then 
      For rows As Integer = 0 To dgvReport.Rows.Count - 1 
       dgvReport2.Rows(rows).Cells(newCol).Value = 
       dgvReport.Rows(rows).Cells(1).Value 
      Next 
     Else 
      For rows As Integer = 0 To dgvReport.Rows.Count - 1 
       dgvReport2.Rows.Add(dgvReport.Rows(rows).Cells(1).Value) 
      Next 
     End If 

替換爲以下

For rows As Integer = 0 To dgvReport.Rows.Count - 1 
    For colcnt As Integer = 0 To dgvReport.Columns.Count - 17 
    dgvReport2.Rows.Add(dgvReport.Rows(rows).Cells(0).Value) 
    Next 
Next 

相關問題