Click to See Complete Forum and Search --> : Index was outside the bounds of the array


Margin
February 17th, 2010, 05:21 PM
Hey all,
I am trying to put a text of textbox1 into richtextbox but apearently i am getting a error saying " Index was outside the bounds of the array."
The code i am using is very simple, here it is : "richTextBox1->Lines[0]=textBox1->Text;"

I wish to solve this error and know why i got it cause everything seems fine to me,
Thanks in advanced.

Alex F
February 18th, 2010, 12:21 AM
Array returned by Lines property is read-only. You can only assign the whole array to the Lines property:

richTextBox1->Lines = gcnew String^ [] { textBox1->Text };

Margin
February 18th, 2010, 10:14 AM
i tried that and i got a error saying " a native array cannot contain this managed type"
for some reason i dont think this is the right way of doing it, isnt there any other ay to write to a line in a richtextbox?
Thanks in advanced

memeloo
February 18th, 2010, 11:28 AM
you have to use the SetValue method to change a particular line or a range of lines.

richTextBox1->Lines->SetValue(.....)

edit: mhmm... somehow it doesn't work either

Alex F
February 18th, 2010, 11:57 AM
Show your code.

Margin
February 18th, 2010, 12:01 PM
I did what you said and i tried this for testing : "richTextBox1->Lines->SetValue("test",0);"
but nothing happens, the richtextbox just stays empty :S ?
Am i using the setvalue function incorrectly :S ?

memeloo
February 18th, 2010, 12:30 PM
I got it :D


this->richTextBox1->Text =
"line1" + Environment::NewLine +
"line2" + Environment::NewLine +
"line3" + Environment::NewLine;

int iLine = 1;
String ^before = (String^)richTextBox1->Lines->GetValue(iLine);
int iFirstChar = richTextBox1->GetFirstCharIndexFromLine(iLine);
richTextBox1->Select(iFirstChar, before->Length);
richTextBox1->SelectedText = "it works!";
String ^after = (String^)richTextBox1->Lines->GetValue(iLine);


I'd suggest to change the topic of this thread to "How to change a line in a RichTextBox"

Margin
February 18th, 2010, 12:36 PM
Thanks it works but do you mind explaining the code a little bit :) ?

memeloo
February 18th, 2010, 12:39 PM
first try to find the methods and properties in the documentation RichTextBox (http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.aspx) and read about them and if you still have problems come back and we'll see ;)

Margin
February 18th, 2010, 12:41 PM
ok, thanks