我正在尝试在textBox1
中显示总计如何编写代码,这些代码会添加sub1
,sub2
,sub3
的总值并显示在{{1} }}。 texBox1
。
我继续收到错误。
而且当我选中第一个标记时,我该如何给它一个特定的值?
mealsub = sub1 + sub2 + sub3
答案 0 :(得分:1)
您只需要在外部范围内声明sub1,..,sub3。这意味着以下代码应该有效:
private void button1_Click(object sender, EventArgs e)
{
string drink = String.Empty;
string burger = String.Empty;
QtextBox1.Enabled = false;
QtextBox2.Enabled = false;
QtextBox3.Enabled = false;
StextBox1.Enabled = false;
StextBox2.Enabled = false;
StextBox3.Enabled = false;
double sub1 = 0,sub2 = 0,sub3 = 0;
if (checkBox1.Checked) //== true)
{
int q1;
int.TryParse(QtextBox1.Text, out q1);
sub1 = q1 * 4.99;
StextBox1.Enabled = true;
StextBox1.Text = sub1.ToString("c");
}
if (checkBox2.Checked)
{
int q2;
int.TryParse(QtextBox1.Text, out q2);
sub2 = q2 * 7.99;
StextBox2.Enabled = true;
StextBox2.Text = sub2.ToString("c");
}
if (checkBox3.Checked)
{
int q3;
int.TryParse(QtextBox1.Text, out q3);
sub3 = q3 * 5.99;
StextBox3.Enabled = true;
StextBox3.Text = sub3.ToString("c");
}
// get selected drink
if (radioButton1.Checked)
drink = "";
else if (radioButton2.Checked)
drink = "";
else if (radioButton3.Checked)
drink = "";
textBox1.Text = mealsub.ToString();
double tax = .098;
string taxtotal = mealsub + tax;
textBox2.Text = tax.ToString();
textBox3.Text = taxtotal.ToString();
textBox1.Text = (sub1 + sub2 + sub3).ToString();
}
有关范围的详细信息,请访问:msdn
答案 1 :(得分:0)
在您的代码中,变量sub1,sub2和sub3的范围仅限于创建它们的if块。
if (checkBox1.Checked) //== true)
{
int q1;
int.TryParse(QtextBox1.Text, out q1);
double sub1 = q1 * 4.99; //sub1 being created here
StextBox1.Enabled = true;
StextBox1.Text = sub1.ToString("c");
}//sub1 does not exist here
if (checkBox2.Checked)
{
int q2;
int.TryParse(QtextBox1.Text, out q2);
double sub2 = q2 * 7.99; //sub2 being created here
StextBox2.Enabled = true;
StextBox2.Text = sub2.ToString("c");
}//sub2 does not exist here
if (checkBox3.Checked)
{
int q3;
int.TryParse(QtextBox1.Text, out q3);
double sub3 = q3 * 5.99; //sub3 being created here
StextBox3.Enabled = true;
StextBox3.Text = sub3.ToString("c");
}//sub3 does not exist here
这意味着一旦执行离开第一个if块,你的sub1变量就会被销毁。为了解决这个问题,你必须在if块之外定义这些变量,最好是在调用函数之后。这样就可以在函数内部访问它们。即
private void button1_Click(object sender, EventArgs e)
{
string drink = String.Empty;
string burger = String.Empty;
double sub1=0 ,sub2=0 ,sub3=0;
//remaining code
您的代码中还有一件事是我无法在任何地方看到enjoyub变量初始化。因此,在if blocks
之后你应该有这样的东西// get selected drink
if (radioButton1.Checked)
drink = "";
else if (radioButton2.Checked)
drink = "";
else if (radioButton3.Checked)
drink = "";
double mealsub=sub1+sub2+sub3;
textBox1.Text = mealsub.ToString();
double tax = .098;
string taxtotal = mealsub + tax;
textBox2.Text = tax.ToString();
textBox3.Text = taxtotal.ToString();
textBox1.Text = (sub1 + sub2 + sub3).ToString();
}
答案 2 :(得分:0)
两个问题。
在外部范围内声明sub1,..,sub3。
double sub1,sub2,sub3; sub1 = 0; sub2 = 0; sub3 = 0; //然后转到块
textBox1.Text = (sub1 + sub2 + sub3).ToString(); // sub1, sub2 and sub3 are double type. You have to convert it to string