2017-08-27 113 views
-1

我有1個標籤和4個複選框。我想要做的是當選中複選框時,我希望價格在文本框中增加或減少,具體取決於複選框是否未選中。我迷失在如何做到這一點上。如何選擇複選框時更改文本框的值C#winforms

標籤TextBlock_Price

複選框有以下幾種:phScreenRepair, virusRemoval, hardwareRepInstall, softwareInstall 我的代碼:

 public float? MultipleServiceAdder() 
    { 
     if (phScreenRepair.Checked) 
     { 
      return 20.00f; 
     } 
     if (virusRemoval.Checked) 
     { 
      return 10.00f; 
     } 
     if (hardwareRepInstall.Checked) 
     { 
      return 10.00f; 
     } 
     if (softwareInstall.Checked) 
     { 
      return 5.00f; 
     } 
     textBlock_Price.Text = "$0.00"; 
     return 0f; 
    } 
+0

您有複選框[的CheckedChanged](https://msdn.microsoft.com/en-us/library/system.windows.forms.checkbox.checkedchanged(V = vs.110)的.aspx)事件。請不要懶惰,並使用谷歌。 –

+0

認爲點擊事件會起作用,CheckStateChanged會是最好的,因爲當您點擊,移動點擊等等時會發生多種事情...... @ bruno.almeida –

回答

0

您可以訂閱checkBox.CheckStateChanged事件,並從那裏更改標籤或文本框的值。您也可以訂閱checkBox.Click事件,但每次點擊都會觸發,但是有一些點擊,例如輪班點擊,可能無意引發事件。

例子:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WindowsFormsApp1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      checkBox1.CheckStateChanged += CheckBox1_CheckStateChanged; 
     } 

     private void CheckBox1_CheckStateChanged(object sender, EventArgs e) 
     { 
      MessageBox.Show("Input Changed!"); 
     } 
    } 
} 
0
float x=0.00f; 
if (phScreenRepair.Checked) x += 20.00f; 
if (virusRemoval.Checked) x += 10.00f; 
if (hardwareRepInstall.Checked) x += 10.00f; 
if (softwareInstall.Checked) x += 5.00f; 

textBlock_Price.Text = x.toString(); 
+0

他正在尋找運行代碼,框被點擊。一旦方法被計時器或其他事物調用,就不會運行代碼。 –

+0

@SeanMitchell他可以在每一處使用這些行checkbox_oncheckedChange事件! – PurTahan

+0

事實確實如此,他可以讓所有人訂閱複選框檢查狀態更改事件,但都運行相同的方法來更改輸出。 –

0

試試這個,但我沒有測試它。 請在每個複選框的checkedchanged事件中調用此方法。

float max = 45.0f; //(20+10+10+5) 

public float? MultipleServiceAdder() 
{ 
    float total; 
    total = max; 
    if (!phScreenRepair.Checked) 
    { 
     total = total - 20.00f; 
    } 
    if (!virusRemoval.Checked) 
    { 
     total = total - 10.00f; 
    } 
    if (!hardwareRepInstall.Checked) 
    { 
     total = total - 10.00f; 
    } 
    if (!softwareInstall.Checked) 
    { 
     total = total - 5.00f; 
    } 

    textBlock_Price.Text = total.ToString(); 
    return total; 
    }