如何将数据网格视图的数据传递给其他表单中的文本框
本文关键字:数据 其他 表单 文本 数据网 网格 视图 | 更新日期: 2023-09-27 18:36:53
Datagridview位于Form2中,TextBoxes位于Form1中。
使用 Show(); 从 Form1 调用窗体 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 加倍。
您需要
在 Form2 中引用 Form1。您可以在 Form2 的构造函数中传递它
private Form1 _form1;
public Form2 (Form1 form1)
{
_form1 = form1;
}
从 Form1 中创建并打开如下所示的 Form2:
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();
但是,如果使用数据绑定,事情会变得更简单。请参见:详细的数据绑定教程
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 }
然后,可以在第二个窗体上调用该方法,从第一个窗体传递所需的值。