2013-12-20 91 views
1

我需要在正確的方向上轉向如何解決這個小問題。從第二種形式填充DataGridView

我有兩種形式。在Form1上,我有空的dataGridView1和一個名爲btnAdd的按鈕。當用戶點擊按鈕時,會顯示Form2(From2.ShowDialog())。在這個form2上我有dataGridView2和一個按鈕btn2。 Datagridview綁定到一個SQL表(它顯示id和名稱列)。當用戶在dataGridView中選擇一行並單擊btn2時,我需要將該行添加到dataGridView1中。我將如何最好地完成這一點。謝謝你的幫助。

這是我有的一些代碼。

// I show new form 
private void btnAdd_Click(object sender, EventArgs e) 
{ 
    Form2 form2 = new Form2(); 
    From2.Text = "some title text"; 
    form2.ShowDialog(this); 
} 

// In form2 I bind data to dataGridView2 and need to add 
// selected item to dataGridView1 
public Form2() 
{ 
    InitializeComponent(); 
    getData(); 
} 

private void getData() 
{ 
    try 
    { 
    String connectionString = "my connection string"; 
    SqlConnection connection = new SqlConnection(connectionString); 
    DataTable data = new DataTable(); 
    SqlDataAdapter da = new SqlDataAdapter("my SQL query", connection); 
    da.Fill(data); 
    dataGridView2.DataSource = data; 
    } 
    catch (SqlException ex) 
    { 
    MessageBox.Show(ex.ToString()); 
    } 
} 

private void btn2_Click(object sender, EventArgs e) 
{ 
    if (dataGridView2.SelectedCells.Count > 0) 
    { 
    int i = dataGridView2.SelectedCells[0].RowIndex; 
    DataGridViewRow r = dataGridView2.Rows[i]; 
    //Need to add selected row to dataGridView1 
    } 
} 

回答

1

您可以使用所有者財產

Form2 form2 = new Form2(dataGridView1); 
     From2.Text = "some title text"; 
form2.Owner=this; 
     form2.ShowDialog(this); 

而且在窗口2;

((Form1)this.Owner).YOURMETHODTOADDROW(your parameter) 

實施YOURMETHODTOADDROW到行添加到網格,然後刷新GRID1

+0

並設置YOURMETHODTOADDROW公共 – Ktt

+0

這並獲得成功,謝謝:) – user1080533

0

您可以將dataGridView1的引用傳遞給Form2,雖然這種事情可以很快讓您的代碼糾結在一起。

public class Form1 : Form 
{ 
    ... 

    private void btnAdd_Click(object sender, EventArgs e) 
    { 
     Form2 form2 = new Form2(dataGridView1); 
     From2.Text = "some title text"; 

     form2.ShowDialog(this); 
    } 
} 

public class Form2 : Form 
{ 
    private DataGridView form1DataGridView; 

    public Form2(DataGridView form1DataGridView) 
    { 
     InitializeComponent(); 

     this.form1DataGridView = form1DataGridView; 

     getData(); 
    } 

    private void btn2_Click(object sender, EventArgs e) 
    { 
     // do something with form1DataGridView 
    } 
}