문제

My task is to input some text in tbUnos and in label1 print out string's first two letters. I've just started learning Visual C++ and I'm trying to figure things out.

private: System::Void textBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) {

      String^ sUnos = tbUnos->Text;
      label1->Text = sUnos->String::Substring(1,2);

}

When built and ran, my program crashed. Please help :)

도움이 되었습니까?

해결책

First of all this is not C++, this is C++/CLI, which is a language extension targeting the CLI.

Second, I don't understand how your program compiles when you do this sUnos->String::Substring. However, your code should look like this:

String^ sUnos = tbUnos->Text;
if(!String::IsNullOrEmpty(sUnos))
   label1->Text = sUnos->Substring(1,2);

EDIT: Notice this code is in the handler for the TextChanged event. That means it is called each time the text changes, like each time you press a key on the keyboard. When you type the first letter in the text box, the tbUnos->Text will contain a single character and Substring(1, 2) will throw because there is no index 1 to start with. From MSDN:

ArgumentOutOfRangeException

startIndex plus length indicates a position not within this instance.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top