我試圖計算取決於是否複選框被選中的特定變量的最終值。然而,這是動態完成的。以列表作爲變量的總和,並在運行時編輯它
我試圖實現:上述
示例工作正常,但它開始去錯了,當我開始取消選中複選框。它減去由時間的雙重量,我不知道爲什麼:
我的代碼(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);
}
}
GUI:
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'。 – juharr
它正在做正確的計算。對於兩個未經檢查的複選框,它將變成-10,對於一個複選框,它的5和它們之和變爲-5。根據你的期望,結果應該是什麼?你不應該做減法,如果你想結果是5. –