Sie sind auf Seite 1von 19

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

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 ******************************************************************************** ************************************* Textbox que admite solo letras Cdigo fuente en un form con un textbox1 Private Sub TextBox1_KeyPress(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventA rgs) _ 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 nmeros o caracteres que quiera Cdigo fuente en el formulario con un textbox1

Private Sub TextBox1_KeyPress(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventA rgs) _ Handles TextBox1.KeyPress If InStr(1, "0123456789,-" & Chr(8), e.KeyChar) = 0 Then e.KeyChar = "" End If End Sub ******************************************************************************** ******************************************** Cambiar el foco al otro textbox al presionar enter Colocar varios varios controles textbox y el siguiente cdigo

Private Sub TextBox1_KeyPress(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventA rgs) _ Handles TextBox1.KeyPress If e.KeyChar = ChrW(Keys.Enter) Then e.Handled = True SendKeys.Send("{TAB}") End If End Sub ******************************************************************************** ******************************************** ejemplo para limitar la edicin de datos de una o varias columnas de un control Da taGridview para ingresar solo valores de tipo numrico

En el ejemplo se llena la grilla con cuatro columnas, donde la columna 1 y la co lumna 3 es para entrada de solo nmeros. Nota: en el evento KeyPress donde se verifca el caracter, ahi se debe indicar el ndice de columna en el cual solo se ingresarn nmeros.

Crear un nuevo proyecto, aadir un windows Form, un control DataGridView llamado D ataGridview1

Cdigo fuente Option Explicit On Option Strict On Public Class Form1 Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' llenar la cuadricula con valores With DataGridView1 .Columns.Clear() ' agregar cabeceras .Columns.Add("Productos", "Productos") .Columns.Add("stock", "stock Actual") .Columns.Add("Fecha", "Fecha") .Columns.Add("Id", "Id Proveedor") Dim random_stock As New Random ' agregar filas For i As Integer = 1 To 20 .Rows.Add("Producto n " & i, _ random_stock.Next(25, 500), _ Date.Now.AddDays(i).ToShortDateString, _ i) Next ' Bloquear la Columna fecha .Columns("fecha").ReadOnly = True End With End Sub Private Sub dataGridView1_EditingControlShowing( _ ByVal sender As Object, _ ByVal e As DataGridViewEditingControlShowingEventArgs) _ Handles DataGridView1.EditingControlShowing ' referencia a la celda Dim validar As TextBox = CType(e.Control, TextBox) ' agregar el controlador de eventos para el KeyPress AddHandler validar.KeyPress, AddressOf validar_Keypress End Sub ' evento Keypress ' ''''''''''''''''''' Private Sub validar_Keypress( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventArgs) ' obtener indice de la columna

Dim columna As Integer = DataGridView1.CurrentCell.ColumnIndex ' comprobar si la celda en edicin corresponde a la columna 1 o 3 If columna = 1 Or columna = 3 Then ' Obtener caracter Dim caracter As Char = e.KeyChar ' comprobar si el caracter es un nmero o el retroceso If Not Char.IsNumber(caracter) And (caracter = ChrW(Keys.Back)) = False Then 'Me.Text = e.KeyChar e.KeyChar = Chr(0) End If End If End Sub End Class ******************************************************************************** ****************************** Ejemplo para poder aceptar el separador decimal para los nmeros Dim columna As Integer = DataGridView1.CurrentCell.ColumnIndex ' verificar columna actual If columna = 1 Or columna = 3 Then Dim caracter As Char = e.KeyChar ' referencia a la celda Dim txt As TextBox = CType(sender, TextBox) ' comprobar si es un nmero con isNumber, si es el backspace, si el caract er ' es el separador decimal, y que no contiene ya el separador If (Char.IsNumber(caracter)) Or _ (caracter = ChrW(Keys.Back)) Or _ (caracter = ",") And _ (txt.Text.Contains(",") = False) Then e.Handled = False Else e.Handled = True End If End If ******************************************************************************** ******************************** Seleccionar todo el texto del control al recibir el foco con el mtodo SelectAll

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 ******************************************************************************** ************************************** Maysculas y minsculas con Upper y Lower

' Maysculas 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 ******************************************************************************** **************************************** Mtodo ReadToEnd - Leer todo el contenido de un archivo de texto y visualizarlo en un texbox ( controles : Un control Button , un textBox1 Multiline ) 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 mtodo 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 dilogo 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 ******************************************************************************** ************************************** Textbox que admite solo letras Cdigo fuente en un form con un textbox1 Private Sub TextBox1_KeyPress(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventA rgs) _ 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 nmeros o caracteres que quiera: (Esta es una forma que de scubr guiandome de el cdigo de vb6, y est bien cortito). Cdigo fuente en el formulario con un textbox1 Private Sub TextBox1_KeyPress(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventA rgs) _ Handles TextBox1.KeyPress If InStr(1, "0123456789,-" & Chr(8), e.KeyChar) = 0 Then e.KeyChar = "" End If End Sub ******************************************************************************** ************************************************

Sencillo ejemplo en vb.net para sumar una columna determinada en un control Data Gridview Para el ejemplo colocar en un formulario dos controles Button, un control Label y un Datagridview

vista previa del formulario para sumar la columna

Cdigo fuente

Option Explicit On Option Strict On Public Class Form1 Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Me.Text = "Sumar columnas en DataGridview" Button1.Text = "Sumar" Button2.Text = "Cargar valores" End Sub ' funcin que retorna el total Private Function Sumar( _ ByVal nombre_Columna As String, _ ByVal Dgv As DataGridView) As Double Dim total As Double = 0 ' recorrer las filas y obtener los items de la columna indicada en " nombre_Columna" Try For i As Integer = 0 To Dgv.RowCount - 1 total = total + CDbl(Dgv.Item(nombre_Columna.ToLower, i).Val ue) Next Catch ex As Exception MsgBox(ex.Message.ToString) End Try ' retornar el valor Return total End Function Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' muostrar el total de la suma en el control Label para la columna l lamada Costo

Label1.Text = "Total :" & Format(Sumar("costo", DataGridView1), "c") .ToString End Sub Private Sub Button2_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Randomize() With DataGridView1 ' Agregar dos columnas .Columns.Clear() .Columns.Add("Id", "Id Producto") .Columns.Add("Costo", "Costo") ' agregar 10 filas .RowCount = 10 ' aadir un valor para el campo ID For Filas As Integer = 0 To .RowCount - 1 .Item(0, Filas).Value = Filas Next ' aadir un valor aleatorio para el campo Costo For Filas As Integer = 0 To .RowCount - 1 .Item(1, Filas).Value = Format(CInt(Rnd() * 2500), "c") Next End With End Sub End Class ******************************************************************************** *********************************** Buscar un registro o fila en una grilla de tipo DataGridView Simple cdigo de ejemplo que usa el mtodo Find del componente BindingSource para bu scar un registro en un campo especfico en una tabla

formulario captura del formulario de ejemplo para buscar las filas en el DataGridview Controles Un control Un control Un control Indicar el Establecer DataGridView llamado DataGridView1 Button llamado Button1 ( botn para buscar ) textBox llamado textBox1 ( para ingresar el dato ) campo por el cual buscar ( Primer parmetro del mtodo Find) la cadena de conexin a utilizar

Cdigo fuente

Option Explicit On Option Strict On Imports System.Data Imports System.Data.SqlClient Public Class Form1 ' ConnectionString para SQL server EXPRESS Private Const cs As String = "Data Source=(local)\SQLEXPRESS;" & _ "Integrated Security=True;" & _ "Initial Catalog=la_base_de_datos" 'Declarar un BindingSource Private BindingSource1 As Windows.Forms.BindingSource = New BindingSourc e Private Sub Form1_FormClosed( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.Form Closed BindingSource1.Dispose() End Sub Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Button1.Text = "Buscar fila" Try ' Declarar la conexin y abrir Using cn As SqlConnection = New SqlConnection(cs) cn.Open() ' Crear un DataAdapter y pasarle el comando para traer los r egistros Dim da As New SqlDataAdapter("SELECT * FROM la_tabla", cn) ' DataTable Dim dt As New DataTable ' llenar el DataTable da.Fill(dt) ' enlazar el DataTable al BindingSource BindingSource1.DataSource = dt ' propiedades para el DataGridview ''''''''''''''''''''''''''''''''''''''' With DataGridView1 ' opcional: Sin seleccin mltiple .MultiSelect = False ' seleccioanr fila completa al hacer clic en un registro .SelectionMode = DataGridViewSelectionMode.FullRowSelect

' enlazar los controles .DataSource = BindingSource1.DataSource End With End Using ' errores Catch ex As Exception MsgBox(ex.Message.ToString) End Try End Sub ' Funcin que retorna el ndice de la fila '' '''''''''''''''''''''''''''''''''''''''''''''''''''' Function Buscar( _ ByVal Columna As String, _ ByVal texto As String, _ ByVal BindingSource As BindingSource) As Integer Try ' si est vacio salir y no retornar nada If BindingSource1.DataSource Is Nothing Then Return -1 End If ' Ejecutar el mtodo Find pasndole los datos Dim fila As Integer = BindingSource.Find(Columna.Trim, texto) ' Mover el cursor a la fila obtenida BindingSource.Position = fila ' retornar el valor Return fila ' errores Catch ex As Exception MsgBox(ex.Message.ToString, MsgBoxStyle.Critical) End Try ' no retornar nada Return -1 End Function ' Botn para buscar en el DataGridView Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' Pasar el nombre del campo por el cual buscar , ' el dato, y el BindingSource enlazado al DataGridView '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ''''''' Dim ret As Integer = Buscar( _ "Nombre", _ TextBox1.Text.Trim, _ BindingSource1) ' si no se encontr .... If ret = -1 Then ' mostrar un mensaje

MsgBox("No se encontr la fila", MsgBoxStyle.Critical) Else With DataGridView1 ' volver a enlazar .DataSource = BindingSource1 ' Pasarle el ndice para Visualizar la fila al comienzo de la grilla .FirstDisplayedScrollingRowIndex = ret End With End If End Sub End Class ******************************************************************************** ***************************************** Ejemplo para actualizar y guardar cambios realizados en un control DataGridview

El ejemplo tiene tres botones , uno para actualizar los cambios realizados en la grilla, otro para eliminar el registro seleccionado y otro para crear uno nuevo

Controles en un windows form Un DataGridview Tres controles Button ( btn_delete, btn_Update, btn_new) para eliminar , gua rdar y crear un nuevo registro Cuatro button ( btn_first, btn_Previous, btn_next y btn_last) para moverse p or los registros de la tabla usando los mtodos MoveFirst , MoveNext etc.. del com ponente Bindingsource Establecer la cadena de conexin y la instruccin sql para cargar la tabla en el datagridview

vista previa del proyecto para guardar y eliminar datos en un datagridview en vb .net

Cdigo fuente

Option Explicit On Option Strict On ' Espacios de nombres ' ''''''''''''''''''''''''''''''''''''''''' Imports System.Data.SqlClient

Public Class Form1 'BindingSource Private WithEvents bs As New BindingSource ' Adaptador de datos sql Private SqlDataAdapter As SqlDataAdapter ' Cadena de conexin Private Const cs As String = "Data Source=(local)\SQLEXPRESS;" & _ "Initial Catalog=demo_bd;" & _ "Integrated Security=true" ' flag Private bEdit As Boolean ' actualizar los cambios al salir ' '''''''''''''''''''''''''''''''''''''''' Private Sub Form1_FormClosing( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.FormClosingEventArgs) _ Handles Me.FormClosing If bEdit Then 'preguntar si se desea guardar If (MsgBox( _ "Guardar cambios ?", _ MsgBoxStyle.YesNo, _ "guardar")) = MsgBoxResult.Yes Then Actualizar(False) End If End If End Sub Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' propiedades del datagrid ' ''''''''''''''''''''''''''''''''''''' With DataGridView1 ' alternar color de filas .AlternatingRowsDefaultCellStyle.BackColor = Color.FloralWhite .DefaultCellStyle.BackColor = Color.Beige ' Establecer el origen de datos para el DataGridview .DataSource = bs End With ' botones ' ''''''''''''''''''''''''''''''''''''' btn_Update.Text = "Guardar cambios" btn_delete.Text = "Eliminar registro" btn_new.Text = "Nuevo" btn_first.Text = "<<" btn_Previous.Text = "<" btn_next.Text = ">" btn_last.Text = ">>"

' cagar los datos cargar_registros("Select * From alumnos Order by Apellido", DataGrid View1) End Sub Private Sub cargar_registros( _ ByVal sql As String, _ ByVal dv As DataGridView) Try ' Inicializar el SqlDataAdapter indicandole el comando y el conn ection string SqlDataAdapter = New SqlDataAdapter(sql, cs) Dim SqlCommandBuilder As New SqlCommandBuilder(SqlDataAdapter) ' llenar el DataTable Dim dt As New DataTable() SqlDataAdapter.Fill(dt) ' Enlazar el BindingSource con el datatable anterior ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' bs.DataSource = dt With dv .Refresh() ' coloca el registro arriba de todo .FirstDisplayedScrollingRowIndex = bs.Position End With bEdit = False Catch exSql As SqlException MsgBox(exSql.Message.ToString) Catch ex As Exception MsgBox(ex.Message.ToString) End Try End Sub ' botn para guardar los cambios y llenar la grilla Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btn_Update.Click Actualizar() End Sub ' Eliminar el elemento actual del BindingSource y actualizar Private Sub btn_delete_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btn_delete.Click If Not bs.Current Is Nothing Then ' eliminar bs.RemoveCurrent()

'Guardar los cambios y recargar Actualizar() Else MsgBox("No hay un registro actual para eliminar", _ MsgBoxStyle.Exclamation, _ "Eliminar") End If End Sub Private Sub Actualizar(Optional ByVal bCargar As Boolean = True) ' Actualizar y guardar cambios If Not bs.DataSource Is Nothing Then SqlDataAdapter.Update(CType(bs.DataSource, DataTable)) If bCargar Then cargar_registros("Select * From alumnos Order by Apellido", DataGridView1) End If End If End Sub Private Sub btn_first_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btn_first.Click, btn_last.Click, btn_next.Click, btn_Pre vious.Click ' Botones para moverse por los registros ' ''''''''''''''''''''''''''''''''''''''''''''' If sender Is btn_Previous Then bs.MovePrevious() ElseIf sender Is btn_first Then bs.MoveFirst() ElseIf sender Is btn_next Then bs.MoveNext() ElseIf sender Is btn_last Then bs.MoveLast() End If End Sub Private Sub DataGridView1_CellEndEdit( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ Handles DataGridView1.CellEndEdit bEdit = True End Sub ******************************************************************************** **************************** Ejecutar comandos sql con ExecuteScalar

Sencillo cdigo de muestra para usar el mtodo ExecuteScalar de Ado.NET y poder cons ultar y recuperar valores desde una base de datos mediante las funciones de sql: Count, Max y Min, Sum etc... El ejemplo conecta a una base de datos de sql , luego se crea un nuevo comando c on una consulta para obtener el valor total con la funcin Count. Por ltimo ejecuta el mtodo ExecuteScalar para retornar el valor total

Cdigo fuente

Option Explicit On Option Strict On ' espacio de nombres Imports System.Data Imports System.Data.SqlClient ' Formulario Public Class Form1 Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'cadena de conexin para la base de datos Const cs As String = "Data Source=(local)\SQLEXPRESS;" & _ "Initial Catalog=la base de datos;" & _ "Integrated Security=true" ' Inicializar Dim conexion As New SqlConnection(cs) Try ' Instanciar un SqlCommand para ejecutar el Select Count Dim cmd As New SqlCommand("Select Count(*) As Total From Cliente s", conexion) ' Ejecutar el Open para Abrir la conexin conexion.Open() Dim total As Integer = 0 ' Ejecutar el mtodo ExecuteScalar y devolver el ' registro pertenciente a la primera columna de la primer fila d el conjunto de datos

total = CType(cmd.ExecuteScalar, Integer) ' convertir el tipo de datos a Integer ' Mostrar el resultado para el Total de Clientes MsgBox("El total de Clientes es :" & total, MsgBoxStyle.Informat ion) Catch exSql As SqlException MsgBox(exSql.Message.ToString) Catch ex As Exception MsgBox(ex.Message.ToString) Finally ' cerrar la conexin anterior If conexion.State = ConnectionState.Open Then conexion.Close() End If End Try End Sub End Class ******************************************************************************* ************************* DataBindings - Enlazar controles Textbox a campos de una tabla Volver - Anterior - Siguiente

Simple ejemplo en Visual basic.NET 2005 para enlazar dos controles textBox a cam pos de una tabla sql usando un BindingManagerBase

Para el proyecto de ejemplo se debe colocar en un windows form dos controles tex tBox. El textBox1 se enlaza con el campo Nombre de la tabla Contactos y el TextBox2 tendr como DataMember el campo "Apellido"

Tambin colocar en el form, tres controles Button: btnPrev para moverse al anterior registro, btnNext para el siguiente y el btnUpdate, para guardar los cambios realizados en el DataSet mediante u n commandBuilder

Formulario vista previa del windows form de ejemplo para enlazar los controles a los campos y poder guardar los cambios en la base de datos

Nota: En el ejemplo, la tabla se llama "Contactos" y el nombre de la base de dat os, se llama "bd"

Cdigo fuente Texto planoImprimir Option Explicit On Option Strict On ' espacios de nombres ' '''''''''''''''''''''''''''''''''' Imports System.Data.SqlClient ' cliente sql Public Class Form1 ' variable con evento para el objeto BindingManagerBase Private WithEvents bmBase As BindingManagerBase ' cadena de conexin ( base de datos demo_bd) Const cs As String = "server=(local)\SQLEXPRESS;" & _ "integrated security=sspi;" & _ "database=" Const catalogo As String = "bd" ' DataSet a nivel de formulario para almacenar los datos Dim Dataset As DataSet Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Try 'Instanciar nueva conexin Using cn As New SqlConnection(cs & catalogo) ' Instruccin Sql para seleccionar los registros de la tabla c ontactos Dim sql As String = "SELECT * FROM contactos" ' Nuevo DataAdapter Dim DataAdapter As New SqlDataAdapter(sql, cn) ' Nuevo ds Dataset = New DataSet ' llenarlo DataAdapter.Fill(Dataset, "contactos") ' enlazar los controles textBox con el Dataset e indicarle ' el DataMember para poder visualizar cada campo ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''

' campo NOMBRE para el textbox1 TextBox1.DataBindings.Add("text", Dataset, "contactos.Nombre ") ' Campo APELLIDO para el textbox2 TextBox2.DataBindings.Add("text", Dataset, "contactos.Apelli dos") bmBase = Me.BindingContext(Dataset, "contactos") If bmBase.Count > 0 Then bmBase.Position = bmBase.Count bmBase.Position = 0 End If End Using Catch exsql As SqlException MsgBox(exsql.Message.ToString, MsgBoxStyle.Critical, "se produjo un error") Catch ex As Exception MsgBox(ex.Message.ToString, MsgBoxStyle.Critical, "se produjo un error") End Try btnPrev.Text = "Anterior" btnNext.Text = "Siguiente" btnUpdate.Text = "Guardar" End Sub ' Siguiente registro Private Sub Button2_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnNext.Click ' Incrementar la propiedad Position del BindingManagerBase bmBase.Position = bmBase.Position + 1 End Sub ' registro anterior Private Sub button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPrev.Click ' decrementar la propiedad Position del BindingManagerBase bmBase.Position = bmBase.Position - 1 End Sub ' Botn para actualizar y guardar los cambios ' '''''''''''''''''''''''''''''''''''''''''''''' Private Sub Button3_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnUpdate.Click ' Crear nuevo objeto OleDbConnection Using cn As New SqlConnection(cs & catalogo) bmBase.EndCurrentEdit()

Try ' Abrir la conexin anterior cn.Open() ' crear un nuevo adaptador de datos para el Dataset Dim DataAdapter As New SqlDataAdapter( _ "select * from contactos", cn) ' Llenar el dataset DataAdapter.Fill(Dataset) ' CommandBuilder para poder actualizar los cambios en la bas e de datos Dim cmdUpdate As New SqlCommandBuilder(DataAdapter) With DataAdapter .UpdateCommand = cmdUpdate.GetUpdateCommand End With ' Ejecutar el mtodo Update del DataAdapter para actualizar DataAdapter.Update(Dataset, Dataset.Tables(0).TableName) MsgBox("Datos actualizados", MsgBoxStyle.Information, "Guard ar") ' Excepciones ' ''''''''''''''''''''''''''''''''''''''''''' Catch exSql As SqlException MsgBox(exSql.Message.ToString, MsgBoxStyle.Critical, "Se pro dujo un error") Catch ex As Exception MessageBox.Show(ex.Message, "Se produjo un error") End Try End Using End Sub ' evento PositionChanged del BindingManagerBase para saber la posicin act ual y el total de filas ' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''' Private Sub bMgr_PositionChanged( _ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles bmBase.PositionChanged Me.Text = "Registro: " & bmBase.Position.ToString & " / " & bmBase.C ount.ToString End Sub End Class ' nuevo registro Private Sub btn_new_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btn_new.Click bs.AddNew() End Sub End Class

Das könnte Ihnen auch gefallen