-1

I want to convert integer from TextBox to another TextBox. I have this code, but it only converts at the beginning, and nothing shappen when I change the TextBox.

int j = 100;
int value = 0;
for (int i = 0; i <= j; i++)
{
    if (AtextBox.Text == i.ToString())
    {
        value = j - i;
        BtextBox.Text = value.ToString();
    }
}

How can BtextBox changes everytime i change the AtextBox?

Yeldar Kurmangaliyev
  • 30,498
  • 11
  • 53
  • 87
Mirza
  • 179
  • 2
  • 16

1 Answers1

2

You need to use events. Create a TextChanged event handler.

There are two ways to do this:

  1. Open designer, open Properties of Atextbox, find TextChanged event and click it twice.
  2. Since TextChanged is default event for TextBox, simply click your TextBox twice in designer

Visual Studio will create the following handler:

public void Atextbox_TextChanged(object sender, EventArgs e) ...

Just add your code to it:

public void Atextbox_TextChanged(object sender, EventArgs e)
{
   int value;
   if (int.TryParse(Atextbox.Text, out value))
   {
       Btextbox.Text = (100 - value).ToString();
   }
}

Every time you change the contents of Atextbox, it will trigger this event, which will parse integer from your textbox, substract it from 100, and apply it to another textbox.
And, yes, you don't need a loop there.

Yeldar Kurmangaliyev
  • 30,498
  • 11
  • 53
  • 87
  • umm the line `Btextbox.Text = (100 - value).ToString();` got error occured : Object reference not set to an instance of an object. why? – Mirza Dec 07 '15 at 05:31
  • @Mirza The only thing that could could happen is that `Btextbox` is null. http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Yeldar Kurmangaliyev Dec 07 '15 at 05:33
  • but its not null, i have default value of Btextbox, i also try to fill `Btextbox.Text = "100"` before if statement, but still got same error – Mirza Dec 07 '15 at 05:35