Home > Software design >  Visual Studio 2022 C How to make a calculator with 2 textboxes to accept ONLY numbers
Visual Studio 2022 C How to make a calculator with 2 textboxes to accept ONLY numbers

Time:10-25

textBox3 is just the result textBox , all i want is a validation check for textBox1 and textBox2 so the only input is numbers

 #pragma endregion

    private: System::Void Calculate(System::Object^ sender, System::EventArgs^ e) {
        if (sender == button_plus) {
            textBox3->Text = Convert::ToString(Convert::ToDouble(textBox1->Text)   Convert::ToDouble(textBox2->Text));
        }
        else if (sender == button_minus) {
            textBox3->Text = Convert::ToString(Convert::ToDouble(textBox1->Text) - Convert::ToDouble(textBox2->Text));
        }
        else if (sender == button_multi) {
            textBox3->Text = Convert::ToString(Convert::ToDouble(textBox1->Text) * Convert::ToDouble(textBox2->Text));
        }
        else if (sender == button_div) {
            textBox3->Text = Convert::ToString(Convert::ToDouble(textBox1->Text) / Convert::ToDouble(textBox2->Text));
        }
        else if (sender == button_exit) {
            this->Close();
        }
    }

CodePudding user response:

I fianlly figured it out i just make a try, catch and solve this one

    private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) {
double num1;
try {
    num1 = System::Double::Parse(this->textBox1->Text);
}
catch (System::Exception^ exception) {
    num1 = 0;
}
this->textBox1->Text = num1.ToString();}
private: System::Void textBox2_TextChanged(System::Object^ sender, System::EventArgs^ e) {
double num2;
try {
    num2 = System::Double::Parse(this->textBox2->Text);
}
catch (System::Exception^ exception) {
    num2 = 0;
}
this->textBox2->Text = num2.ToString();}
  • Related