我有這個 (if-else if-else) 陳述句它作業正常,除了 else 部分我不知道為什么?
void TakeAction()
{
try
{
if (chkProduct.Checked == true && chkMaterial.Checked == false)
{
InsertProduct();
MessageBox.Show("Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
else if (chkProduct.Checked == false && chkMaterial.Checked == true)
{
InsertMaterial();
MessageBox.Show("Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
else if (chkProduct.Checked == true && chkMaterial.Checked == true)
{
InsertSubProduct();
MessageBox.Show("Done", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
// else if (chkProduct.CheckState == CheckState.Unchecked && chkMaterial.CheckState == CheckState.Unchecked) // Tried this also still nothing
else
//Doesn't work
{
MessageBox.Show("Check even one Checkbox", "Choose", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception Err)
{
MessageBox.Show("This Error Occured :" Err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
我嘗試了不同的方法,例如 else、else if 最后是代碼中的注釋行。提前致謝。
Edit#1 我認為這個方法會干擾TakeAction
方法并導致問題,我會從頭除錯我的代碼,謝謝
if (chkProduct.Checked == true && chkMaterial.Checked == false)
{
da = new SqlDataAdapter("SELECT [ProductCode] FROM Products Where [ProductCode] = @prcode ", Cn);
da.SelectCommand.Parameters.AddWithValue("@prcode", txtcode.Text);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//int cnt = Convert.ToInt32(dt.Rows[0]["ProductCode"].ToString());
MessageBox.Show("Duplicated", "Duplicated");
}
else
{
//MessageBox.Show("No problem , Its not Product");
TakeAction();
}
}
//the first If >> If Material Or SubProduct
else if (chkMaterial.Checked == true)
{
da = new SqlDataAdapter("SELECT Code FROM Items Where Code = @prcode ", Cn);
da.SelectCommand.Parameters.AddWithValue("@prcode", txtcode.Text);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Duplicated", "Duplicated");
}
else
{
// MessageBox.Show("No problem , Its not item");
TakeAction();
}
uj5u.com熱心網友回復:
您總共有4種不同的組合:
chkProduct.Checked : chkMaterial.Checked : Action
--------------------------------------------------------------
true : true : InsertSubProduct()
true : false : InsertMaterial()
false : true : InsertProduct()
false : false : Ask User to Check
這就是為什么您不必將最后一個條件設定為else if
:else
就足夠了。如果您在除錯時遇到問題,您可以將代碼更改為nesting if
并將最后一個條件向前推:
if (!chkProduct.Checked && !chkMaterial.Checked)
MessageBox.Show("Check even one Checkbox",
"Choose",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
else {
if (chkProduct.Checked)
if (chkMaterial.Checked)
InsertSubProduct();
else
InsertProduct();
else
InsertMaterial();
MessageBox.Show("Done",
"Done",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
Close();
}
uj5u.com熱心網友回復:
如果 else 陳述句不起作用,則意味著 else if 陳述句之一被命中。你試過斷點嗎?您還可以洗掉 true 和 false 值以使其更具可讀性。
代替:
if (x == true && y == false) { }
您可以執行以下操作:
if (x && !y) { }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/469416.html
下一篇:C#自定義組態檔(一)