2016-03-01 68 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 } 

然后,您可以打电话给你的第二个窗体上的方法,使您从第一种形式要求的值。

相关问题