2016-03-01 26 views
1

Datagridview位於Form1中的Form2,TextBoxes中。如何將datagridview的數據傳遞給其他表單中的文本框?

用Show()從Form1中調用Form 2;其中位於dataGridView,然後將此信息傳遞給Form1中的文本框。在窗體2

代碼示例:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
    Form1 exportar = new Form1(); 
    exportar.textBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString(); 
    exportar.comboBox1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString(); 
    exportar.textBox2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString(); 
    exportar.textBox3.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[3].Value.ToString(); 
    exportar.textBox4.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[4].Value.ToString(); 
    exportar.dateTimePicker1.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[5].Value.ToString(); 
    exportar.dateTimePicker2.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[6].Value.ToString(); 
    exportar.textBox7.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[7].Value.ToString(); 
    exportar.textBox8.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[8].Value.ToString(); 
    exportar.textBox9.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[9].Value.ToString(); 
    exportar.textBox10.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[11].Value.ToString(); 
} 

這沒有工作,但是當我把exportar.Show()傳遞的信息。問題是,Form1增加了一倍。

+0

您是否使用類似_Form2的方式從Form1調用Form2 f2 = new Form2(); f2.Show(); _? – Steve

+0

是的,我喜歡。使用Show()調用Form 2;在哪裏找到dataGridView,然後將這些信息傳遞給Form1。 – Ale

+0

那麼從Olivier Jacot-Descombes先生那裏得到的答案是正確的。您將Form 1的實例傳遞給被調用的Form 2實例。這允許Form2內的代碼正確引用TextBoxes可見的窗體。你不應該創建Form1的另一個實例 – Steve

回答

2

您需要Form2的Form1的引用。你可以通過它在窗體2

的構造
private Form1 _form1; 

public Form2 (Form1 form1) 
{ 
    _form1 = form1; 
} 

你喜歡這個從內部Form1中創建和打開窗體2:

var form2 = new Form2(this); 
form2.ShowDialog(this); 

爲了能夠訪問其他形式的控制,你必須在屬性窗口中將其Modifer更改爲Internal

那麼你可以這樣設置值:

var row = dataGridView1.CurrentRow; // This is "the row". 
            // No detour through the index is necessary. 
_form1.textBox1.Text = row.Cells[0].Value.ToString(); 
_form1.comboBox1.Text = row.Cells[1].Value.ToString(); 

但是事情變得更簡單,如果你使用數據綁定。請參閱:A Detailed Data Binding Tutorial

+0

非常感謝! – Ale

0

1.Pass它作爲cunstrctor參數:

public Form2(string text){ 
     Textbox1. text = text; 
} 

Form2 f = new Form2("something to send to the form"); 
f.Show(); 

2.創建一個公共屬性爲窗體2:

public string TheText {get{return TextBox1.Text;}; set {textBox1.Text = value;};} 

,然後從第一形式:

Form2 f = new Form2(); 
f.TheText = "Some text"; 
f.Show(); 
0

要麼傳遞其他表單的構造函數中的數據(如果它是必需的)。或者在您的其他表單中提供公開的方法,以便您可以單獨設置數據。

E.g.

public void setTextBoxData(String text) { ,etc, etc } 

然後,您可以打電話給你的第二個窗體上的方法,使您從第一種形式要求的值。

相關問題