Vb.Net Create TextBoxes At Runtime - Allow Only Numerical Input

Vb.Net Create TextBoxes At Runtime - Allow Only Numerical Input

isocam
Collaborator Collaborator
95 Views
1 Reply
Message 1 of 2

Vb.Net Create TextBoxes At Runtime - Allow Only Numerical Input

isocam
Collaborator
Collaborator

Can anybody help?

 

I am creating a Vb.Net "Addin" for Inventor that automatically creates several TextBoxes at runtime.

 

Does anybody know how I can allow only number input on all the TextBoxes I create?

 

Normally, I would use a routine such as Private Sub TextBox.Keypress(.....) for each TextBox I create in the Form design, however, I am creating several TextBoxes at runtime and do not know how to allow numerical input only on all the TextBoxes that are created at runtime.

 

Many thanks in advance!

 

Darren

0 Likes
96 Views
1 Reply
Reply (1)
Message 2 of 2

Michael.Navara
Advisor
Advisor

You can create new TextBox and assign the event handler at runtime. See the sample iLogic rule bellow

AddReference "System.Drawing.dll"
Imports System.Windows.Forms

Sub Main
	Dim testForm = New TestForm()
	For i As Integer = 0 To 5
		Dim numericBox = New System.Windows.Forms.TextBox
		AddHandler numericBox.TextChanged, AddressOf textBox_TextChanged
		testForm.tlpTextBoxes.Controls.Add(numericBox)
	Next
	testForm.ShowDialog()
End Sub

Private Sub textBox_TextChanged(sender As Object, e As EventArgs)
	Dim textBox As System.Windows.Forms.TextBox = sender
	Dim newValue As Integer
	If (Integer.TryParse(textBox.Text, newValue)) Then
		textBox.Tag = newValue
	Else
		textBox.Text = textBox.Tag
        textBox.Select(textBox.Text.Length, 0)
	End If
End Sub


Public Class TestForm
	Inherits System.Windows.Forms.Form
	Public WithEvents tlpTextBoxes As TableLayoutPanel

	Public Sub New()
		InitializeComponent()
	End Sub

	Private Sub InitializeComponent()
		Me.tlpTextBoxes = New System.Windows.Forms.TableLayoutPanel()
		Me.SuspendLayout()
		'
		'tlpTextBoxes
		'
		Me.tlpTextBoxes.ColumnCount = 1
		Me.tlpTextBoxes.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100.0!))
		Me.tlpTextBoxes.Dock = System.Windows.Forms.DockStyle.Fill
		Me.tlpTextBoxes.Location = New System.Drawing.Point(0, 0)
		Me.tlpTextBoxes.Name = "tlpTextBoxes"
		Me.tlpTextBoxes.RowCount = 2
		Me.tlpTextBoxes.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
		Me.tlpTextBoxes.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20.0!))
		Me.tlpTextBoxes.Size = New System.Drawing.Size(284, 261)
		Me.tlpTextBoxes.TabIndex = 0
		'
		'TestForm
		'
		Me.ClientSize = New System.Drawing.Size(284, 261)
		Me.Controls.Add(Me.tlpTextBoxes)
		Me.Name = "TestForm"
		Me.ResumeLayout(False)

	End Sub

End Class
0 Likes