如何设置textBox以自动将数字转换为double

时间:2015-11-20 19:54:16

标签: c# .net winforms double

我的问题是:当您点击另一个文本框时,如何设置文本框以自动将数字转换为双倍?

例如:如屏幕截图所示,我单击button1在textbox1中输入1,当您单击textbox2时,1将在textbox1中转换为1.00。然后在textbox1中输入12,然后在单击textbox2时将其转换为12.00。

现在的问题是:我在textbox1中插入1,当我将2插入textbox1(它应该是12)时,文本框删除1并插入2.现在textbox1只包含数字2,当我单击textbox2时,textbox1转换2至2.00

我的意思是我想通过点击button1然后按钮2来形成数字12,但我不能因为我插入1而当我插入2时前一个1被删除。我认为这是因为当我点击button2时会执行textBox1_Leave方法。 我不知道如何解决它。

我只希望textbox1在单击textbox2时将任何输入的数字转换为double。我希望我解释得很好,请帮助我。谢谢

Screen shot

public partial class Form1 : Form
{

    private TextBoxBase SelectedBox = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        textBox1.Focus();  //set textbox1 focused when form loads
        SelectedBox = textBox1;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        SelectedBox.Focus(); // set the current textbox focused.

        SendKeys.Send("1");

    }

    private void button2_Click(object sender, EventArgs e)
    {
        SelectedBox.Focus();

        SendKeys.Send("2");

    }

    private void textBox1_Enter(object sender, EventArgs e) // to set focus textbox1
    {
        SelectedBox = sender as TextBox;
        this.ActiveControl = textBox1;
        textBox1.Focus();

    }

    private void textBox2_Enter(object sender, EventArgs e)// to set focus textbox2
    {
        SelectedBox = sender as TextBox;
        this.ActiveControl = textBox2;
        textBox2.Focus();
    }



    private void textBox1_Leave(object sender, EventArgs e)   // to convert any number in textbox1 to double once textbox2 is clicked
    {
        double d = Convert.ToDouble(textBox1.Text);
        textBox1.Text = d.ToString("0.00");
        SelectedBox = sender as TextBox;

    }
}

3 个答案:

答案 0 :(得分:0)

您可以将此方法用作文本框{/ 1}}事件的处理程序

Leave

答案 1 :(得分:0)

 void textBox1_textchange(object sender, EventArgs e) // to set focus textbox1
    {
        if(textBox1.focused() && textBox1.Text.toString()!="")
            TextBox2.Text=Convert.ToDouble(textBox1.Text).to string();

     }



 void textBox2_textchange(object sender, EventArgs e) // to set focus textbox1
    {
        if(textBox2.focused() && textBox2.Text.toString()!="")
            TextBox1.Text=Convert.ToDouble(textBox2.Text).to string();

     }

答案 2 :(得分:-1)

好的,我花了2个多小时后解决了这个问题。

删除textBox1_Leave事件,并在textBox2_Enter事件中添加以下代码。

double d = Convert.ToDouble(textBox1.Text);
    textBox1.Text = d.ToString("0.00");