lunes, 12 de abril de 2010

Ejemplos varios para trabajar con controles textbox en visual basic.net

1 - Textbox que admite solo letras
Código fuente en un form con un textbox1

Texto planoCopiar código fuenteImprimir
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

If Char.IsLetter(e.KeyChar) Then
e.Handled = False
ElseIf Char.IsControl(e.KeyChar) Then
e.Handled = False
ElseIf Char.IsSeparator(e.KeyChar) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

If Char.IsLetter(e.KeyChar) Then
e.Handled = False
ElseIf Char.IsControl(e.KeyChar) Then
e.Handled = False
ElseIf Char.IsSeparator(e.KeyChar) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub

Textbox que admite solo números o caracteres que quiera: (Esta es una forma que descubrí guiandome de el código de vb6, y está bien cortito).
Código fuente en el formulario con un textbox1

Texto planoCopiar código fuenteImprimir
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If InStr(1, "0123456789,-" & Chr(8), e.KeyChar) = 0 Then
e.KeyChar = ""
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If InStr(1, "0123456789,-" & Chr(8), e.KeyChar) = 0 Then
e.KeyChar = ""
End If
End Sub

Enlace relacionado : Ingresar solo números en DatagridView
--------------------------------------------------------------------------------

2 - Cambiar el foco al otro textbox al presionar enter
Colocar varios varios controles textbox y el siguiente código

Texto planoCopiar código fuenteImprimir
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = ChrW(Keys.Enter) Then
e.Handled = True
SendKeys.Send("{TAB}")
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = ChrW(Keys.Enter) Then
e.Handled = True
SendKeys.Send("{TAB}")
End If
End Sub

3 - Seleccionar todo el texto del control al recibir el foco con el método SelectAll

Texto planoCopiar código fuenteImprimir
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TextBox1.SelectAll()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = " Un texto "
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TextBox1.SelectAll()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = " Un texto "
End Sub

4 - Evitar el BEEP al apretar Enter

Texto planoCopiar código fuenteImprimir
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = Convert.ToChar(Keys.Return) Then
e.Handled = True
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = Convert.ToChar(Keys.Return) Then
e.Handled = True
End If
End Sub

5 - Mayúsculas y minúsculas con Upper y Lower

Texto planoCopiar código fuenteImprimir
' Mayúsculas
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TextBox1.CharacterCasing = CharacterCasing.Upper
End Sub

'Minusculas :

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TextBox1.CharacterCasing = CharacterCasing.Lower
End Sub
' Mayúsculas
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TextBox1.CharacterCasing = CharacterCasing.Upper
End Sub

'Minusculas :

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TextBox1.CharacterCasing = CharacterCasing.Lower
End Sub

6 - Guardar el texto de un textbox en un archivo .txt
Colocar un control Button

Texto planoCopiar código fuenteImprimir
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
' Crea el archivo
FileOpen(1, "c:\texto.txt", OpenMode.Output)
' escribe el contenido
Write(1, TextBox1.Text)
FileClose(1) ' lo cierra
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
' Crea el archivo
FileOpen(1, "c:\texto.txt", OpenMode.Output)
' escribe el contenido
Write(1, TextBox1.Text)
FileClose(1) ' lo cierra
End Sub

7 - ReadLine - Leer lineas de un archivo de texto
Ejemplo lee desde un fichero .txt (ubicado en la carpeta debug ) todas las lineas y las visualiza en unos controles textbox

Formulario que mediante un botón abre un diálogo para seleccionar un archivo de texto, y leer mediante el método ReadLine del objeto StreamReader, todas las líneas y visualziarlas en un control textBox

Colocar un control textbox multilinea, un control button y un control openFileDialog

Texto planoCopiar código fuenteImprimir
Option Strict On
' espacio de nombre para poder usar StreamReader
Imports System.IO

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Button1.Text = " Abrir archivo "
End Sub

Function Leer(ByVal path As String) As String
Try
Dim oSR As StreamReader = New StreamReader(path)

Dim l As String
Dim tempSTR As String = ""
' lee la primer línea
l = oSR.ReadLine()
While Not l Is Nothing
' variable temporal que almacena las líneas
tempSTR = tempSTR & l & vbNewLine
l = oSR.ReadLine() ' lee la siguiente
End While
' cierra y libera los recursos
oSR.Close()
oSR.Dispose()
' retorna el texto
Return tempSTR
' errores
Catch oe As Exception
Return ""
MsgBox(oe.Message)
End Try

End Function

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
With OpenFileDialog1
.FileName = ""
.Filter = "Archivos de texto *.txt|*.txt|Todos *.*|*.*"
' abre el diálogo para seleccionar archivo el de texto
.ShowDialog()

If .FileName <> "" Then
TextBox1.Text = Leer(.FileName)
End If
End With
End Sub
End Class
Option Strict On
' espacio de nombre para poder usar StreamReader
Imports System.IO

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Button1.Text = " Abrir archivo "
End Sub

Function Leer(ByVal path As String) As String
Try
Dim oSR As StreamReader = New StreamReader(path)

Dim l As String
Dim tempSTR As String = ""
' lee la primer línea
l = oSR.ReadLine()
While Not l Is Nothing
' variable temporal que almacena las líneas
tempSTR = tempSTR & l & vbNewLine
l = oSR.ReadLine() ' lee la siguiente
End While
' cierra y libera los recursos
oSR.Close()
oSR.Dispose()
' retorna el texto
Return tempSTR
' errores
Catch oe As Exception
Return ""
MsgBox(oe.Message)
End Try

End Function

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
With OpenFileDialog1
.FileName = ""
.Filter = "Archivos de texto *.txt|*.txt|Todos *.*|*.*"
' abre el diálogo para seleccionar archivo el de texto
.ShowDialog()

If .FileName <> "" Then
TextBox1.Text = Leer(.FileName)
End If
End With
End Sub
End Class


8 - Método ReadToEnd - Leer todo el contenido de un archivo de texto y visualizarlo en un texbox
( controles : Un control Button , un textBox1 Multiline )

Texto planoCopiar código fuenteImprimir
Option Explicit On
Option Strict On
Imports System.IO

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Me.Text = "Ejemplo del método ReadToEnd"
Button1.Text = "Abrir archivo de texto "
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

' nuevo diálogo
Dim OpenFiledlg As New OpenFileDialog
With OpenFiledlg
.Title = "Seleccionar archivo de texto"
.Filter = "Archivos de texto *.txt|*.txt"
Try
If .ShowDialog = Windows.Forms.DialogResult.OK Then
Dim datos As New StreamReader(.FileName)
' lee todo el contenido y lo asigna al textbox
TextBox1.Text = datos.ReadToEnd
datos.Close() ' cierra
End If
' error
Catch oMen As Exception
MsgBox(oMen.Message, MsgBoxStyle.Critical)
End Try
End With
End Sub
End Class
Option Explicit On
Option Strict On
Imports System.IO

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Me.Text = "Ejemplo del método ReadToEnd"
Button1.Text = "Abrir archivo de texto "
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

' nuevo diálogo
Dim OpenFiledlg As New OpenFileDialog
With OpenFiledlg
.Title = "Seleccionar archivo de texto"
.Filter = "Archivos de texto *.txt|*.txt"
Try
If .ShowDialog = Windows.Forms.DialogResult.OK Then
Dim datos As New StreamReader(.FileName)
' lee todo el contenido y lo asigna al textbox
TextBox1.Text = datos.ReadToEnd
datos.Close() ' cierra
End If
' error
Catch oMen As Exception
MsgBox(oMen.Message, MsgBoxStyle.Critical)
End Try
End With
End Sub
End Class

9 - Limpiar todo el contenido de los textbox de un formulario
Ejemplo que recorre mediante un bucle For Each todos los objetos Textbox que se encuentran en el form indicado para eliminar el contenido

Agregar algunos TextBox, un Button

Texto planoCopiar código fuenteImprimir
Imports System.Windows.Forms

Public Class Form1

Private Sub Limpiar_Cajas(ByVal f As Form)
' recorrer todos los controles del formulario indicado
For Each c As Control In f.Controls
If TypeOf c Is TextBox Then
c.Text = "" ' eliminar el texto
End If
Next
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
' pasar el formulario
Call Limpiar_Cajas(Me)

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Button1.Text = "Limpiar textBox"
End Sub
End Class

1 comentario: