(我目前正在服用c#,但我从未参加过任何必备课程,所以请原谅我有限的理解。)
到目前为止,我所看到的答案并不是我对这个项目所需要的。
这是我到目前为止所做的:
// Form1
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
string strStatus = "";
if (rdoMarr.Checked)
{
strStatus = "Married";
}
else
{
strStatus = "Single";
}
string strPrint = "Marital Status = " + strStatus + "\n Pay Period =" + cbPayPd.Text + "\n Dependents =" + cbAllow.Text + "\n Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text + "\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text + "\n Net = " + txtNet.Text;
var form2 = new Print(strPrint);
form2.Show();
}
我的Form2需要什么才能收到此字符串?
答案 0 :(得分:0)
有很多方法可以做到这一点。下面的那个不是我推荐的,但我认为这是最容易理解的。
这是实现此目的的一种方法:
Form1
类上创建一个公共静态属性以保存此变量的值MessageBox
文本EventHandler
方法
TextChanged
个对象的TextBox
事件连接到#4中创建的公共EventHandler
Form2
时引用#2中的属性
Label
label1
以下是:
public partial class Form1 : Form
{
// 1. This class-level variable will hold our string
public static string PrintMessage { get; private set; }
// 2. Reference your strPrint variable for the MessageBox as you were before
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(PrintMessage);
}
// 3. This method will update our string with values from TextBoxes
private void UpdateText()
{
PrintMessage = "Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text +
"\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text +
"\n Net = " + txtNet.Text;
}
// 4. Call our update method when the Form loads
private void Form1_Load(object sender, EventArgs e)
{
UpdateText();
}
// 5. This EventHandler just calls our update method
private void CommonTextChangedEvent(object sender, EventArgs e)
{
UpdateText();
}
// I have a `button1` on my Form1, and clicking this button shows Form2
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2();
form2.Show();
}
现在,挂钩事件处理程序。最简单的方法是: