Reputation: 4021
I want to keep a string to another string strTotal from a richtextbox. then i want to split it into two SubString like firstPart and secondPart by a middle index say: midIndex.
Then I want to change some value in firsthalf and join with secondhalf. And finally show it to the richTextBox.
For this i used this code:
For my Last debug:
rtxtQueryPan.Text.Length = 53; midIndex = 45;
//string Totalqueryy = rtxtQueryPan.Text;
string firstHalf = rtxtQueryPan.Text.Substring(0, midIndex-2);
string secondHalf = rtxtQueryPan.Text.Substring((midIndex- 1), (rtxtQueryPan.Text.Length - 1)); // THIS LINE SHOWS ERROR
string duplicateFirstHalf = firstHalf;
firstHalf += " " + clColumnNames.Text + ",";
rtxtQueryPan.Text = firstHalf+secondHalf;
In the 3rd Line of the code says:
Index and length must refer to a location within the string. Parameter name: length
I have checked the length, midIndexvalue etc. But found no clue.
Upvotes: 0
Views: 1088
Reputation: 39833
C#'s .Substring
function takes a length, not a position as its second argument.
Thus, you probably wanted to write the following code:
rtxtQueryPan.Text.Substring(midIndex-1, (rtxtQueryPan.Text.Length-1) - midIndex);
Also, the length argument is optional, and not something you should provide in your case, as you want the rest of the string included. You can also therefore write:
rtxtQueryPan.Text.Substring(midIndex-1);
Upvotes: 4
Reputation: 23833
Substring
can only work in the bounds of the string being acted upon. Here, rtxtQueryPan.Text
refers to the text in the RichTextBox
which is longer that the text currently held in the string. Remember the arguments of Substring
are the start position and length.
You want (rtxtQueryPan.Text.Length-1) - midIndex
as the second argument.
I hope this helps.
Upvotes: 1
Reputation: 179
The problem is your grabbing the second string from the half way through and saying i want the entire string. if you use substring the second pramater is the length of your substring. this should fix it.
string secondHalf = rtxtQueryPan.Text.Substring((midIndex- 1),
(rtxtQueryPan.Text.Length - 1-midIndex));
Upvotes: 1