我无法通过点击按钮将多个文本框的数据从Form1
传递到Form2
。我尝试了以下方法,但它无法正常工作。
我做错了吗?如果是这样,我该怎么做?
Form1代码:
public partial class Form1: Form {
Form2 frm2;
public Form1() {
InitializeComponent();
}
private void btnInvoice_Click_1(object sender, EventArgs e) {
this.Hide();
if(frm2==null)
frm2=new Form2();
frm2.ValueFromForm1(txtFirstName.Text);
frm2.ValueFromForm1(txtLastName.Text);
frm2.ValueFromForm1(txtCellNo.Text);
frm2.ValueFromForm1(txtDate.Text);
frm2.ValueFromForm1(txtDueDate.Text);
frm2.Show();
}
}
Form2代码:
public partial class Form2: Form {
public Form2() {
InitializeComponent();
}
public void ValueFromForm1(string value) {
txtFirstName.Text=value;
txtLastName.Text=value;
txtCellNo.Text=value;
txtMaskDueDate.Text=value;
txtMaskDate.Text=value;
}
}
答案 0 :(得分:7)
您正在为所有文本框分配相同的值。结果将是您要分配的最后一个值(即txtDueDate
文本)。创建不同的方法为每个文本框分配值,或将值作为数组或自定义对象传递:
public class Invoice
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CellNo { get; set; }
// etc
}
在Form1上
private void btnInvoice_Click_1(object sender, EventArgs e)
{
this.Hide();
if (frm2 == null)
frm2 = new Form2();
Invoice invoice = new Invoice();
invoice.FirstName = txtFirstName.Text;
invoice.LastName = txtLastName.Text;
invoice.CellNo = txtCellNo.Text;
// etc
frm2.Invoice = invoice;
frm2.Show();
}
在Form2上
public Invoice Invoice
{
set
{
txtFirstName.Text = value.FirstName;
txtLastName.Text = value.LastName;
txtCellNo.Text = value.CellNo;
// etc
}
}
答案 1 :(得分:1)
在Properties
中创建Form2
怎么样?创建class
是解决方案之一,但您可以简单地创建Properties
到get
和set
private void btnInvoice_Click_1(object sender, EventArgs e)
{
this.Hide();
using(var f = new Form2())
{
f.FirstName = txtFirstName.Text;
f.LastName = txtLastName.Text;
f.CellNo = txtCellNo.Text;
f.ShowDialog();
}
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string CellNo { get; set; }
private void Form2_Load(object sender, EventArgs e)
{
txtFirstName.Text = FirstName;
txtLastName.Text = LastName;
txtCellNo.Text = CellNo;
}
答案 2 :(得分:-1)
方法实现是非常错误的,或者至少是你想到的逻辑!您正在为所有文本框分配相同的值。
您可以通过两种方式解决问题。
private
更改为internal
或public
。更改修饰符后,您可以将其称为private void btnInvoice_Click_1(object sender, EventArgs e)
{
this.Hide();
if (frm2 == null)
frm2 = new Form2();
frm2.txtFirstName.Text = txtFirstName.Text;
frm2.txtLastName.Text = txtLastName.Text;
frm2.txtCellNo.Text = txtCellNo.Text;
frm2.txtDate.Text = txtDate.Text;
frm2.txtDueDate.Text = txtDueDate.Text;
frm2.Show();
}
public void ValueForFirstName(string value)
{
txtFirstName.Text = value;
}
public void ValuForLastName(string value)
{
txtLastName.Text = value;
}