2014-09-01 78 views
1

我有2個GridView控件。我需要將選中的行從一個GridView添加到第二個GridView。 (我通過點擊直接到GridView從GridView中選擇一行。)從一個gridview添加選定的行到另一個

這是我的代碼,但它將所有數據從gridview1複製到gridview2。我只需要選定的行。

private void button6_Click(object sender, EventArgs e) 
    { 
     DataGridViewColumn newCol = null; 
     foreach (DataGridViewColumn col in dataGridView1.Columns) 
     { 
      newCol = new DataGridViewColumn(col.CellTemplate); 
      newCol.HeaderText = col.HeaderText; 
      newCol.Name = col.Name; 
      dataGridView2.Columns.Add(newCol); 
     } 

     dataGridView2.RowCount = dataGridView1.RowCount; 
     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      foreach (DataGridViewColumn col in dataGridView1.Columns) 
      { 
       dataGridView2.Rows[row.Index].Cells[col.Name].Value = row.Cells[col.Name].Value; 
      } 
     } 

我填充dataGridView1與一個DataTable:

設置 dataGridView1.DataSource
SqlConnection con = new SqlConnection(@"Data Source=AFZAL\SQLEXPRESS;Initial Catalog=GIMS_LabInfo;Integrated Security=True"); 
con.Open(); 
SqlCommand sc = new SqlCommand("SELECT PROFCODE,PROFNAME FROM PROFNAMES$ WHERE (PROFNAME LIKE '" + textBox1.Text + "%') AND PROFCODE NOT IN (SELECT PROFCODE FROM MAP) ORDER BY Profname desc ", con); 
sc.ExecuteNonQuery(); 
SqlDataAdapter sda = new SqlDataAdapter(sc); 
DataTable data = new DataTable(); 
sda.Fill(data); 
dataGridView1.DataSource = data; 
+1

你能否提供一些你現有的代碼? – 2014-09-01 15:23:56

+0

請參閱上面我的代碼。 – 2014-09-01 15:31:32

+0

它將網格視圖1中的所有數據複製到網格視圖2,但我只需要選定的行。 – 2014-09-01 15:32:36

回答

0

立即:

dataGridView1.DataSource = yourDataTable; 

設置dataGridView2.DataSource克隆第一DataTable的結構(如列):

dataGridView2.DataSource = yourDataTable.Clone(); 

或者:

dataGridView2.DataSource = ((DataTable)dataGridView1.DataSource).Clone(); 

然後在你點擊按鈕時,所有你需要的是這樣的:

private void button6_Click(object sender, EventArgs e) 
{ 
    if (dataGridView1.CurrentRow == null) 
     return; 

    var currentRow = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row; 

    ((DataTable)dataGridView2.DataSource).ImportRow(currentRow); 
} 

我如何在添加多行每次點擊?現在,當我選擇第二行時,它將替換dataGridView2中的第一行。

如果您有多個選定的行,則必須迭代SelectedRows屬性。試試這個:

private void button1_Click(object sender, EventArgs e) 
{ 
    if (dataGridView1.CurrentRow == null) 
     return; 

    foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
     ((DataTable)dataGridView2.DataSource).ImportRow(((DataRowView)row.DataBoundItem).Row); 
} 
+0

非常感謝。它現在正在工作。你能指導我嗎?我怎樣才能每次點擊添加多行。現在,當我選擇第二行時,它將替換dataGridView2中的第一行。每次當我點擊按鈕時,它應該添加dataGridView2中的記錄。提前致謝。 – 2014-09-02 08:25:33

+0

我用可能的解決方案編輯了我的答案。看看是否有效。 – 2014-09-02 11:03:08

+0

親愛的格蘭特溫尼,非常感謝您的幫助,但我仍然沒有得到我想要的輸出。我真正想要的是:當我在dataGridview1中選擇行並按下按鈕時,應該在dataGridview2中添加選定的行(s)。上面的代碼是這樣做的。但是,當我選擇下一行並再次按下按鈕時,它應該是dataGridview2中現有行的添加(不應替換先前添加的行)。 簡而言之,行(s)應該在每個按鈕按下時逐個添加。 請幫忙。我感謝你的努力。 :) – 2014-09-03 22:46:06

相關問題