Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Should a String Bulder Be Used Here 1

Status
Not open for further replies.

Auguy

Programmer
May 1, 2004
1,206
US
I set up a context menu item for some of my text boxes that inserts the current date at the current cursor position in the text box. I normally use a string builder when concatenating strings but don't know if this situation warrants it. The code looks something like
Code:
myBox.Text = Left(myBox.Text, SelStart) + NowDateTime.ToString("MM/dd/yyyy") + " -" + Mid(myBox.Text, SelStart + 1)
myBox.SelectionStart = SelStart + 13
SelStart is the current cursor position and NowDateTime is the curent datetime. Should I use a string builder here?

Auguy
Sylvania/Toledo Ohio
 
Personally I would do it like this:

Code:
	Private Sub InsertDateToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles InsertDateToolStripMenuItem.Click

		Dim NowDateTime As Date = DateTime.Now
		Dim SelStart As Integer = TextBox1.SelectionStart
		TextBox1.Text = TextBox1.Text.Insert(SelStart, NowDateTime.ToString("MM/dd/yyyy") & " -")
		TextBox1.SelectionStart = SelStart + 12

	End Sub

and say no, you don't need a StringBuilder
 
I would guess that you would also need to determine whether the cursor was in the middle of a word or between words.

I omitted your +1 and therefore changed +13 to +12 because of my comment above, and visually ensured appropriate spacing for the insertion.
 
Thanks, I should have used insert to begin with. Your code is much cleaner.

Auguy
Sylvania/Toledo Ohio
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top