protected void btnView_Click(object sender, EventArgs e)
{
int StudentAdmissionNo = Convert.ToInt32(txtAdmissionNo.Text);
string StudentName = txtStudentName.Text;
DateTime DateOfBirth = Convert.ToDateTime(txtDOB.Text);
string Gender = txtGender.Text;
string Standard = txtstandard.Text;
string Section = txtSection.Text;
int Telugu = Convert.ToInt32(txtTelugu.Text);
int English = Convert.ToInt32(txtEnglish.Text);
int Mathematics = Convert.ToInt32(txtMathematics.Text);
//int Total = Convert.ToInt32(lblTot.Text);
//double Average = Convert.ToDouble(lblAve.Text);
string Result = lblRes.Text;
lblTot.Text = (txtTelugu.Text + txtEnglish.Text + txtMathematics.Text); # Total in coming if i enter the 45 65 65 = its coming 456565 like i did wrong?
lblAve.Text = ((lblTot.Text) / 3.00); //This also gives an error
}
在此代码中,我有一个来自lblTot =
添加标记的错误,它与打印我输入的数字和平均值也不起作用一样。
您正在连接文本。当您将 + 与文本/字符串一起使用时,它充当连接运算符。
您需要先将文本转换为整数以进行算术运算。
使用 Convert.ToInt32(输入(;
用以下行替换代码应该可以修复它。
lblTot.Text = (Convert.ToInt32(txtTelugu.Text) + Convert.ToInt32(txtEnglish.Text) + Convert.ToInt32(txtMathematics.Text)).ToString();
lblAve.Text = ((Convert.ToInt32(lblTot.Text)) / 3.00).ToString();
更新
我刚刚注意到您已经在这里为整数分配了所需的值:
int Telugu = Convert.ToInt32(txtTelugu.Text);
int English = Convert.ToInt32(txtEnglish.Text);
int Mathematics = Convert.ToInt32(txtMathematics.Text);
这是正确的,您只需要添加这些变量,例如:
int total = Telugu + English + Mathematics;
lblTot.Text = total.ToString();
然后,平均而言,只需使用我们刚刚将值分配给的total
变量:
lblAve.Text = Convert.ToString(Convert.ToDouble(total / 3.00)); // convert the average to double as you may get values with decimal point. And then convert it back to string in order to assign it to a Label control.
如果我对您要执行的操作的假设是正确的,那么您的代码应该如下所示。
decimal total = Teluga + English + Mathematics;
decimal average = (Teluga + English + Mathematics) / 3.00;
lblTot.Text = total.ToString();
lblAve.Text = average.ToString();
您正在尝试使用字符串来执行数学运算,但这不起作用。
此外,通常
int x = Int32.TryParse(txtEnglish.Text)
是将字符串转换为整数的更好方法
这两个问题的根源都是文本框。文本属性是一个string
。
在你的第一个问题中,你正在连接字符串,这就是为什么它给你456565。
在第二个问题中,您正在尝试对字符串和数字执行算术运算。
通过声明一个Int32
变量占位符并在string
上使用 TryParse 方法,将字符串转换为数字,如下所示:
Int32 txtTeluguResult;
Int32.TryParse(txtTelugu.Text, txtTeluguResult);
另请注意,如果 TryParse 无法成功解析文本输入,它将为您的结果变量输入 0。您可能希望改用Convert.ToInt32()
,如果失败,则会引发 FormatException,具体取决于您想要的行为。
lblTot.Text = (txtTelugu.Text + txtEnglish.Text + txtMathematics.Text); # Total in coming if i enter the 45 65 65 = its coming 456565 like i did wrong?
lblAve.Text = ((lblTot.Text) / 3.00); this also giving error?
您正在使用的字符串变量不是整数、实数或十进制
做类似的事情
lblTot.Text = (((int)txtTelugu.Text + (int)txtEnglish.Text + (int)txtMathematics.Text)).ToString();
lblAve.Text = (((int)(lblTot.Text) / 3.00)).ToString(); this also giving error?