【发布时间】:2017-07-07 13:51:29
【问题描述】:
我正在尝试计算取决于是否选中复选框的特定变量的最终值。然而,这是动态完成的。
我想要达到的目标:
上面的例子工作正常,但是当我开始取消选中复选框时它开始出错。它减去了两倍的时间,我不知道为什么:
我的代码(TimeSpent 是我最后想要的变量):
类
public class Activity
{
public int ID { get; set; }
public int IncidentID { get; set; }
public string Description { get; set; }
public int TimeSpent { get; set; }
public static int StartX { get; set; } = 10;
public static int StartY { get; set; } = 10;
private TextBox textBox = null;
private CheckBox checkBox = null;
public Activity(int iD, int incidentID, string description, int timeSpent)
{
this.ID = iD;
this.IncidentID = incidentID;
this.Description = description;
this.TimeSpent = timeSpent;
}
public Activity()
{ }
public bool isChecked() {
return checkBox.Checked;
}
public void setTimeSpent(int timeSpent) {
this.TimeSpent = timeSpent;
textBox.Text = timeSpent.ToString();
}
public int getTimeSpent()
{
return Int32.Parse(textBox.Text);
}
public void DrawToForm(Panel p)
{
var label = new Label();
textBox = new TextBox();
checkBox = new CheckBox();
checkBox.Checked = true;
textBox.Size = new System.Drawing.Size(40, 20);
label.Text = Description.ToString();
label.AutoSize = true;
textBox.Text = TimeSpent.ToString();
label.Left = StartX;
label.Top = StartY;
StartX += 430;// Move position to right
textBox.Left = StartX;
textBox.Top = StartY;
StartX += 160;// Move position to right
checkBox.Left = StartX;
checkBox.Top = StartY;
StartX = 10;// Reset to start
StartY += 50;// Move position to down
p.Controls.Add(label);
p.Controls.Add(textBox);
p.Controls.Add(checkBox);
}
}
图形界面:
private void Btn_Validate_Click(object sender, EventArgs e)
{
tb_TotalTime.Text = calculateTotalTime().ToString();
}
public int calculateTotalTime()
{
int total = 0;
foreach (Activity a in activities)
{
if(a.isChecked())
{
total += a.getTimeSpent();
}else
{
total -= a.getTimeSpent();
}
}
return total;
}
为什么减法没有正确完成?
【问题讨论】:
-
在图片中看起来一切正常。具体问题是什么?
-
检查时加,非检查时减去 -5-5+5 等于 -5。我想你只是想要添加所以删除
else。 -
计算正确。对于两个未选中的复选框,它变为 -10,对于一个选中的复选框,它的 5 和它们的总和变为 -5。根据您的期望,结果应该是什么?如果您希望结果为 5,则不应进行减法。
标签: c# subtraction