【问题标题】:How to change value of textbox when a checkbox is selected C# winforms选中复选框时如何更改文本框的值 C# winforms
【发布时间】:2018-02-05 03:51:14
【问题描述】:

我有 1 个标签和 4 个复选框。我想要做的是当一个复选框被选中时,我希望文本框中的价格根据复选框是否未选中而增加或减少。我不知道如何做到这一点。

标签是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;
    }

【问题讨论】:

  • 您有复选框CheckedChanged 事件。请不要偷懒,使用谷歌。
  • 认为点击事件会起作用,CheckStateChanged 会是最好的,因为当您点击、移动点击等时会发生多种事情......@bruno.almeida

标签: c# winforms checkbox textbox


【解决方案1】:

您可以订阅 checkBox.CheckStateChanged 事件并从那里更改标签或文本框的值。您也可以订阅 checkBox.Click 事件,但这会在每次点击时触发,但有些点击(如 shift 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!");
        }
    }
}

【讨论】:

    【解决方案2】:
    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 事件!
    • 没错,他实际上可以让所有人都订阅复选框检查状态更改事件,但都运行相同的方法来更改输出。
    【解决方案3】:

    试试这个,但我还没有测试过。 请在每个复选框的 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      相关资源
      最近更新 更多