我一直在为学校开发一个程序,我正在尝试使用构造函数在C#中的表单之间传输字符串。我正在使用的方法在从1转换为2时工作,但现在无法将form2转换为3.该代码用于十个问题的数学测验。感谢
public Form2()
{
InitializeComponent();
}
public Form2(string name, string age)
{
InitializeComponent();
int Score;
int QNUM;
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void button1_Click( int answer, string name, string age, int score, int QNUM, object sender, EventArgs e)
{
if (age == "Year 3")
{
Random rnd = new Random();
int Number1 = rnd.Next(1, 51);
int Number2 = rnd.Next(1, 51);
int Answer = Number1 + Number2;
label4.Text = Convert.ToString(Number1 + " + " + Number2);
}
if( textBox1.Text == Convert.ToString(answer))
{
score = score + 1;
}
if (textBox1.Text == Convert.ToString(answer))
{
score = score + 1;
}
QNUM = QNUM + 1;
label2.Text = Convert.ToString(QNUM);
if ( QNUM == 1)
{
button1.Text = "Next";
}
if (QNUM == 9)
{
button1.Text = "Finish";
}
if (QNUM == 11)
{
Form3 Name2 = new Form3 (name, score);
Name2.Show();
}
}
}
}
我也将代码放在第三种形式
public Form3()
{
InitializeComponent();
}
public Form3(string name, string score)
{
InitializeComponent();
{
}
}
答案 0 :(得分:1)
您已经有了一个良好的开端,但您的代码存在一些问题:
name
不在方法button1_Click
的范围内。您从Form2
构造函数接收参数,但从未设置它。score
是int
,而不是string
。Click
事件处理程序传递参数。这是不可能的。改为使用类变量。将此用于Form2
构造函数:
private string Name {get;set;}
private int Score {get;set;}
public Form2(string name, string age)
{
InitializeComponent();
this.Name = name;
this.Score = 0;
}
这适用于您的Form3
构造函数:
private string Name {get;set;}
private int Score {get;set;}
public Form3(string name, int score)
{
InitializeComponent();
this.Name = name;
this.Score = score;
}
public Form3() : this("defaultName", 0)
{ }
然后像这样调用构造函数:
Form3 Name2 = new Form3 (this.Name, this.Score);
然后修复您的Click
事件处理程序:
private void button1_Click(object sender, EventArgs e)