在Winforms C#中同时触发两个Textchanged事件

时间:2013-04-02 05:21:02

标签: c# winforms events textchanged

当我输入第一个文本框时,它应该运行一个出现在第二个文本框中的转换,当我输入第二个时,它将出现在第一个文本框中。但是,当我输入第一个textchanged事件时,它会触发第二个,这会中断第一个,反之亦然。是否有一种方法可以禁用在突出显示的事件时触发textchanged事件?

public void dB10_TextChanged(object sender, EventArgs e)
    {
        TextBox dB10 = sender as TextBox;
        double dBV;
        int i = dB10.Text.Trim().Length;

        if (i > 0)
        {
            dBV = Convert.ToDouble(dB10.Text);
        }
        else
            return;

       UnitConverter dBConverter = new UnitConverter();

       // Controls for if various radiobuttons were clicked
        if (dBVRadio.Checked == true)
        {
            dBV = dBConverter.dBVToVolts(dBV);
            voltage.Text = dBV.ToString(); 
         }

        else if (dBuRadio.Checked == true)
        {
            dBV = dBConverter.dBuToVolts(dBV);
            voltage.Text = dBV.ToString();
        } 
    }

   public void voltage_TextChanged(object sender, EventArgs e)
    {
        TextBox voltage = sender as TextBox; //V >> dB10 (dBV/dBu)

        int i = voltage.Text.Trim().Length;
        double volts;

        if (i > 0)
        {
            volts = Convert.ToDouble(voltage.Text);
        }
        else
            return;

        UnitConverter dBConverter = new UnitConverter();

            if (dBVRadio.Checked == true)
            {
                dBuRadio.Checked = false;

                volts = dBConverter.voltsTodBV(volts);
                dB10.Text = volts.ToString(); 
            }

            else if (dBuRadio.Checked == true)
            {
                volts = dBConverter.voltsTodBu(volts);
                dB10.Text = volts.ToString();
            }
    }

2 个答案:

答案 0 :(得分:0)

你可以删除另一个文本框的处理程序,然后添加它

public void dB10_TextChanged(object sender, EventArgs e)
{
    voltage.TextChanged-= voltage_TextChanged;
    TextBox dB10 = sender as TextBox;
    double dBV;
    int i = dB10.Text.Trim().Length;

    if (i > 0)
    {
        dBV = Convert.ToDouble(dB10.Text);
    }
    else
        return;

   UnitConverter dBConverter = new UnitConverter();

   // Controls for if various radiobuttons were clicked
    if (dBVRadio.Checked == true)
    {
        dBV = dBConverter.dBVToVolts(dBV);

     }

    else if (dBuRadio.Checked == true)
    {
        dBV = dBConverter.dBuToVolts(dBV);

    } 
   voltage.Text = dBV.ToString();
   voltage.TextChanged+= voltage_TextChanged;


}

答案 1 :(得分:0)

您可以使用bool变量:

bool escape = false;

public void dB10_TextChanged(object sender, EventArgs e)
{
    if(escape)
        return;

    escape = true;
    // your code
    escape = false;
}

public void voltage_TextChanged(object sender, EventArgs e)
{
    if(escape)
        return;

    escape = true;
    // your code
    escape = false;
}