Hi,
I have placed a button, label and a text box on a form. In the button's event handler I have written the following code:
int cost;
int money;
Label->Show("Insert " + cost + " pence");
money = textBox->Text;
When I try to output text to the label I get the following compiler error:
error C2660: 'System::Windows::Forms::Control::Show' : function does not take 1 arguments
Also when I try to assign an int variable entered in text box I get following error:
error C2440: '=' : cannot convert from 'System::String ^' to 'int'error
Even if I try to cast from String to int I get error:
money = (int)textBox->Text;
C2440: 'type cast' : cannot convert from 'System::String ^' to 'int'
I would be grateful if someone could show me how to get round these errors.
AlanPosted Apr 30, 2008, 3:23 PM
Hi Ray,
To ensure that only digits (or backspace) are entered and that Int::Parse won't throw an exception, I'd handle the textBox's KeyPress event as follows:
private
: System::Void textBox_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) { if ((e->KeyChar < 48 && e->KeyChar != 8)|| e->KeyChar > 57){
e->Handled =
true;}
}
ray donaPosted Apr 30, 2008, 1:23 PM
Alan,
Thanks very much for your help. I forgot to ask a further question. In :
if
(textBox->Text != ""){
money = Int32::Parse(textBox->Text);
}
how can I ensure that each time something is entered it is a digit, and if not to reject it.
AlanPosted Apr 29, 2008, 2:19 PM
Firstly, you need to be setting the Label's Text property rather than calling the Show() method.
To convert a numeric string to it's integer representation you can use the static Int32::Parse() method:
Label->Text =
"Insert " + cost + " pence"; if (textBox->Text != ""){
money = Int32::Parse(textBox->Text);
}