如何选择复选框时更改文本框的值C#winforms
我有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;
}
您可以订阅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!");
}
}
}
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();
他正在寻找运行代码,框被点击。一旦方法被计时器或其他事物调用,就不会运行代码。 –
@SeanMitchell他可以在每一处使用这些行checkbox_oncheckedChange事件! – PurTahan
事实确实如此,他可以让所有人订阅复选框检查状态更改事件,但都运行相同的方法来更改输出。 –
试试这个,但我没有测试它。 请在每个复选框的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;
}
您有复选框[的CheckedChanged](https://msdn.microsoft.com/en-us/library/system.windows.forms.checkbox.checkedchanged(V = vs.110)的.aspx)事件。请不要懒惰,并使用谷歌。 –
认为点击事件会起作用,CheckStateChanged会是最好的,因为当您点击,移动点击等等时会发生多种事情...... @ bruno.almeida –