[英]How can I pass data of datagridview to textboxes in other Form?
Datagridview位于Form2的Form1中的TextBoxes中。
使用Show()从Form1调用Form 2; dataGridView位于何处,然后将此信息传递到Form1中的文本框。
Form2中的代码示例:
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加倍。
您需要在Form2中引用Form1。 您可以在Form2的构造函数中传递它
private Form1 _form1;
public Form2 (Form1 form1)
{
_form1 = form1;
}
您可以在Form1中创建并打开Form2,如下所示:
var form2 = new Form2(this);
form2.ShowDialog(this);
为了能够访问其他窗体的控件,必须在属性窗口Modifer
其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();
但是,如果使用数据绑定,事情会变得更简单。 请参阅: 详细的数据绑定教程
1.将其作为cunstrctor参数传递:
public Form2(string text){
Textbox1. text = text;
}
和
Form2 f = new Form2("something to send to the form");
f.Show();
2.为Form2创建一个公共属性:
public string TheText {get{return TextBox1.Text;}; set {textBox1.Text = value;};}
然后从第一种形式开始:
Form2 f = new Form2();
f.TheText = "Some text";
f.Show();
如果是强制性的,则将数据传递到其他形式的构造函数中。 或者以其他形式提供公共方法,该方法允许您分别设置数据。
例如
public void setTextBoxData(String text) { ,etc, etc }
然后,您可以在第二种形式上调用该方法,并从第一种形式传递所需的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.