taji01
taji01

Reputation: 2615

Texbox Copies Another Textbox in C#

I'm using WinForm. I have 2 textboxes.

Goal: I want textBox1 to mirror the numbers I type in textBox2

Problem: All numbers work, except when I type in 0 in the beginning.

Test Case:

textBox1 = 1203 - correct works

textBox2 = 1203 - correct works


textBox1 = 0123 - works

textBox2 = 123 - Does not match textBox1

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            int numb1, result;

            numb1 = Convert.ToInt32(textBox1.Text);
            result = numb1;

            textBox2.Text = result.ToString();

        }
        catch (Exception)
        {
            textBox2.Text = "";
        }
    }

Upvotes: 0

Views: 124

Answers (2)

1SaeedSalehi
1SaeedSalehi

Reputation: 373

try this:

textBox1.Text = int.Parse(textBox2.Text) == 0 ? "0" : textBox2.Text;

Upvotes: 0

Steve
Steve

Reputation: 216323

That's expected due the conversion of your Text string to a number. A leading zero is meaningless in a number and when you convert that number back to a string there will be no leading zero. So, just copy the Text property without conversion.

However, if this code is a tentative to validate the input then use Int32.TryParse instead of Convert.ToInt32

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int numb1;
    if(Int32.TryParse(textBox1.Text, out numb1))
        textBox2.Text = textBox1.Text;
    else
    {
        MessageBox.Show("Invalid number");
        textBox2.Text = "";
    }
}

Int32.TryParse remove the necessity to use a try/catch because if the conversion fails it just return false. Instead Convert.ToInt32 raises an exception. In general terms, if you have the possibility to avoid an exception, then use that possibility instead of drive your logic catching excetions

Upvotes: 3

Related Questions