Reputation: 3
I'm stuck with this calculator.
I have a big textbox with multiline option in true.
I want to click on the button 1 and print the number one in the second line of my textbox. For this the only thing I could find is:
Select Case CType(sender, System.Windows.Forms.Button).Name
Case "Btn1"
TextBox1.Text = Environment.NewLine
TextBox1.Text += CStr(1)
'.....
End Select
But if the number needs to be "11" and thus I must click the same button more than once or even "13" if I click another number then the whole text changes to that specific number. I want to concatenate the second line of my textbox.
I want to save the first line for later purposes
If I try TextBox1.Lines(1) = "1" I get the following error "Index was outside the bounds of the array"
I've been with this for days, please give me a hand.
Upvotes: 0
Views: 456
Reputation: 39122
You could do something like this:
Private Sub Buttons_Click(sender As Object, e As EventArgs) Handles Btn1.Click, Btn2.Click, _
Btn3.Click, Btn4.Click, Btn5.Click, Btn6.Click, Btn7.Click, Btn8.Click, Btn9.Click, Btn0.Click
Dim lines As New List(Of String)(TextBox1.Lines)
While lines.Count < 2
lines.Add("")
End While
lines(1) = lines(1) & DirectCast(sender, Button).Text
TextBox1.Lines = lines.ToArray
End Sub
Answering a question from the comments:
Why do I need to use an array of strings instead of just using the second line of my textbox?
The lines of the TextBox are stored internally in an Array. That's simply how Microsoft decided to implement it. Unfortunately, arrays do not automatically grow in size if you attempt to access a position at an index that is outside of its bounds (larger than its initially declared size). Thus if your TextBox did not have a second line in it already, then you would be accessing an index that is "out of bounds" causing the error. What I've used is a List, which can grow to however big you need it. I initialize the List with the contents of the internal array, then add blank lines to it to ensure it has at least two lines. This approach will preserve the lines that are already in the TextBox. Once I am sure the List has at least two lines, it is safe to access the second line and modify it. Once the List has been built and the second line modified, I convert it back to an Array and reassign it to the TextBox.
Upvotes: 0
Reputation: 15813
Create a variable (say, s
, for this example) that contains the number string only, such as "1", "11", or "137327".
When you click on a number to append to the number string, assign this to the textbox along with the newline character:
s &= CStr(n)
TextBox1.Text = Environment.NewLine & s
It seems nonstandard to require a blank line in a textbox. Make sure that's what you really want to do.
Upvotes: 0