Informática a domicilioIr a diccionario de terminos...Informática a domicilio

Inicio

Trucos VB.NET

Prácticas VB.NET

Manuales VB6

Trucos VB6

Prácticas VB6

 

Dim pokoapoko as String = "Creada el 24/11/2011 actualizo cada semana +/- jeje" & "GRACIAS"

Informática a domicilio

TextBox que admite solo letras:

    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 los caracteres que deseemos.

    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

Canviar el foco de un TextBox al presionar enter.

    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

Seleccionar todo el texto del control al recibir el foco con el método 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

Evitar el BEEP al apretar Enter

    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

Mayúsculas y minúsculas con Upper y Lower

    ' 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  

Guardar el texto de un textbox en un archivo .txt

     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

 ReadLine - Leer lineas de un archivo de texto

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

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

Método ReadToEnd - Leer todo el contenido de un archivo de texto y visualizarlo en un texbox

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

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

Como descargar y subir archivos, hacer ping y chequear si hay conexión a intenet en vb.net

Método DownloadFile

Formulario que usa el método DownloadFile del objeto My.Computer.Network para descargar un archivo desde una url indicada

Asi tiene que quedar el formulario...

Controles

Un control Button

Un control textbox llamado txt_Url

Un control textbox llamado txt_path_destino

 Function Descargar_Archivo(ByVal Url As String, _

                                 ByVal Path_Destino As String) As Boolean

        If Url = vbNullString Or Path_Destino = vbNullString Then

            MsgBox("No se indicó la url o el archivo de destino", _

                    MsgBoxStyle.Critical, "Error")

        Else

            If Len(Dir(Path_Destino)) <> 0 Then

                MsgBox("el archivo destino ya existe.Elija otro destino diferente", _

                                                MsgBoxStyle.Exclamation, "Error")

            Else

                On Error Resume Next

                My.Computer.Network.DownloadFile(Url, Path_Destino)

                If Err.Number = 0 Then

                    Descargar_Archivo = True

                Else

                    MsgBox(Err.Description)

                End If

                Err.Clear()

            End If

        End If

    End Function

    Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) _

                           Handles MyBase.Load

        Button1.Text = "Download"

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _

                              ByVal e As System.EventArgs) Handles Button1.Click

        Dim ret As Boolean

        ret = Descargar_Archivo(txt_url.Text, txt_path_destino.Text)

        If ret Then

            MsgBox("Archivo descargado correctamente", MsgBoxStyle.Information)

        End If

    End Sub

Método UploadFile

Este ejemplo coloca un archivo en la dirección ftp indicada, mostrando el diálogo de progreso modal de windows

Asi queda el formulario...

Private Sub Descargar_Archivo(ByVal Url As String, _

                                   ByVal Path_Archivo As String, _

                                   ByVal usuario As String, _

                                   ByVal password As String)

        ' Controlador de error

        Try

            ' Ejecuta el método UploadFile para subir el archivo

            My.Computer.Network.UploadFile(Path_Archivo, _

                                           Url, _

                                           usuario, _

                                           password, _

                                           True, _

                                           2500, _

                                           FileIO.UICancelOption.DoNothing)

            MessageBox.Show("Archivo enviado con éxito", "", _

                            MessageBoxButtons.OK, MessageBoxIcon.Information)

            ' error

        Catch mensaje As Exception

            MessageBox.Show(mensaje.Message, "", _

                            MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) _

                           Handles MyBase.Load

        Button1.Text = "Upload"

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _

                              ByVal e As System.EventArgs) Handles Button1.Click

        ' le pasa la dirección de destino, el archivo origen, el user y password

        Call Descargar_Archivo("Dirección ftp + el nombre del archivo de destino", _

                               "Ruta del archivo a subir", _

                               "User", _

                               "pass")

    End Sub

My.Computer.Network.IsAvailable - saber si hay conexión a internet

Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) _

                           Handles MyBase.Load

        If My.Computer.Network.IsAvailable = True Then

            MsgBox("Está conectado a internet")

        Else

            MsgBox("No Está conectado a internet")

        End If

    End Sub

My.Computer.Network.Pin - Hacer ping a una web

Sub Hacer_Ping(ByVal URL As String)

        Dim El_Ping As Boolean 'declaramos la variable

        ' verifica que hay conexión a internet

        If My.Computer.Network.IsAvailable = False Then

            MsgBox("No hay conexión a internet", MsgBoxStyle.Critical)

            Exit Sub

        End If

        On Error Resume Next

        'guardamos en la variable la direccion del ping

        El_Ping = (My.Computer.Network.Ping(URL))

        'Acá mandamos los mensajes para las 2 posibilidades

        If El_Ping = False Then

            'si no se pudo acceder ,avisamos

            MsgBox("La Web no está disponible", MsgBoxStyle.Critical, "Error")

        Else

            MsgBox("La Web está disponible !!", MsgBoxStyle.Information, "Aviso")

        End If

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _

                              ByVal e As System.EventArgs) Handles Button1.Click

        Dim Url As String

        Url = InputBox("Ingrese la url", "Ping")

        If Url <> "" Then

            Hacer_Ping(Url)

        End If

    End Sub

Contar archivos en un directorio

    Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) _

                           Handles MyBase.Load

        Try

            Dim ContadorDeArchivos As System.Collections.ObjectModel.ReadOnlyCollection(Of String)

            'le indicamos el path que queremos

            ContadorDeArchivos = My.Computer.FileSystem.GetFiles("C:\WINDOWS")

            'nos devuelve la cantidad de archivos

            MsgBox("La Cantidad de Archivos es: " & CStr(ContadorDeArchivos.Count))

            ' error

        Catch oExcep As Exception

            MsgBox("Descripción del error : " & _

                   oExcep.Message, MsgBoxStyle.Critical, "Error")

        End Try

    End Sub

Crear un archivo vacío ( método Create - objeto System.IO.File )

    Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) Handles MyBase.Load

        Try

            Dim Archivo As System.IO.FileStream

            ' crea un archivo vacio prueba.txt

            Archivo = System.IO.File.Create("c:\Prueba.txt")

            ' error

        Catch oe As Exception

            MsgBox(oe.Message, MsgBoxStyle.Critical)

        End Try

    End Sub

Crear un archivo plano y añadirle texto ( método WriteLine del objeto StreamWriter. Espacio de nombres System.IO )

Option Explicit On

Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) _

                           Handles MyBase.Load

        Dim oSW As New StreamWriter("C:\archivo_prueba.txt")

        Dim Linea As String = "Línea de texto " & vbNewLine & "Otra linea de texto"

        oSW.WriteLine(Linea)

        oSW.Flush()

    End Sub

End Class

My.Computer.FileSystem.GetFiles - Listar archivos

Ejemplo que carga y lista en un control listbox, los archivos de una carpeta

    Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) Handles MyBase.Load

        Try

            ' lista todos los archivos dll del directorio windows _

            ' SearchAllSubDirectories : incluye los Subdirectorios

            ' SearchTopLevelOnly : para buscar solo en el nivel actual

            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

            For Each Archivo As String In My.Computer.FileSystem.GetFiles( _

                                    "c:\windows", _

                                    FileIO.SearchOption.SearchAllSubDirectories, _

                                    "*.dll")

                ListBox1.Items.Add(Archivo)

            Next

            ' errores

        Catch oe As Exception

            MsgBox(oe.Message, MsgBoxStyle.Critical)

        End Try

    End Sub

My.Computer.FileSystem.FindInFiles - Buscar dentro de un fichero

     Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) Handles MyBase.Load

        Try

            Dim Archivo As System.Collections.ObjectModel.ReadOnlyCollection(Of String)

            ' busca "Hola mundo" en un solo nivel ( SearchTopLevelOnly ) en el directorio c:

            Archivo = My.Computer.FileSystem.FindInFiles( _

                                        "C:\", _

                                        "Hola Mundo", _

                                        True, _

                                        FileIO.SearchOption.SearchTopLevelOnly)

            ' recorre la lista

            For Each name As String In Archivo

                ' Agrega

                ListBox1.Items.Add(name)

            Next

            ' error

        Catch oe As Exception

            MsgBox(oe.Message, MsgBoxStyle.Critical)

        End Try

    End Sub

     Comprobar si un directorio o archivo Existe

Option Explicit On

Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles MyBase.Load

        ' Directory

        If Directory.Exists("c:\windows") Then

            MsgBox("La carpeta existe", MsgBoxStyle.Information)

        Else

            MsgBox("No existe", MsgBoxStyle.Information)

        End If

        If File.Exists("c:\windows\explorer.exe") Then

            MsgBox("Existe", MsgBoxStyle.Information)

        Else

            MsgBox("No existe", MsgBoxStyle.Information)

        End If

    End Sub

End Class

Renombrar un archivo

Option Explicit On

Public Class Form1

    Private Sub Form1_Load( _

        ByVal sender As System.Object, _

        ByVal e As System.EventArgs) Handles MyBase.Load

        ' ruta del archivo y el nuevo nombre

        Dim sPath As String = "c:\archivo.txt"

        Dim sNuevoNombre As String = "archivo_Renombrado.txt"

        Try

            ' Renombrarlo con la función renameFile

            My.Computer.FileSystem.RenameFile(sPath, sNuevoNombre)

            MsgBox("Ok.", MsgBoxStyle.Information, "Renombrar archivo")

            ' errores

        Catch ex As Exception

            MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)

        End Try

    End Sub

End Class

Mover un archivo

Option Explicit On

Public Class Form1

    Private Sub Form1_Load( _

        ByVal sender As System.Object, _

        ByVal e As System.EventArgs) Handles MyBase.Load

        ' ruta del archivo origen y el nuevo path y nombre

        Dim sArchivoOrigen As String = "c:\archivo.txt"

        Dim sRutaDestino As String = "d:\archivo.txt"

        Try

            ' Mover el fichero.si existe lo sobreescribe

            My.Computer.FileSystem.MoveFile(sArchivoOrigen, _

                                            sRutaDestino, _

                                            True)

            MsgBox("Ok.", MsgBoxStyle.Information, "Mover archivo")

            ' errores

        Catch ex As Exception

            MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)

        End Try

    End Sub

End Class

Eliminar archivos y carpetas

Option Explicit On

Public Class Form1

    Private Sub Form1_Load( _

        ByVal sender As System.Object, _

        ByVal e As System.EventArgs) Handles MyBase.Load

        Try

            ' Eliminar el archivo, mostrando el cuadro

            'de diálogo de eliminar de windows para confirmar

            Dim sdir As String = "c:\Nueva carpeta"

            Dim Spath As String = "c:\archivo.txt"

            ' Archivo

            My.Computer.FileSystem.DeleteFile( _

                Spath, _

                FileIO.UIOption.AllDialogs, _

                FileIO.RecycleOption.SendToRecycleBin, _

                FileIO.UICancelOption.DoNothing)

            ' carpeta

            My.Computer.FileSystem.DeleteDirectory( _

                sdir, _

                FileIO.UIOption.AllDialogs, _

                FileIO.RecycleOption.SendToRecycleBin, _

                FileIO.UICancelOption.DoNothing)

            ' errores

        Catch ex As Exception

            MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)

        End Try

    End Sub

End Class

Crear un archivo temporal

Option Explicit On

Public Class Form1

    Private Sub Form1_Load( _

        ByVal sender As System.Object, _

        ByVal e As System.EventArgs) Handles MyBase.Load

        Try

            ' crea el archivo en el directorio temp del usuario

            Dim sTempFile As String = My.Computer.FileSystem.GetTempFileName.ToString

            ' muestra la ruta

            MsgBox("Archivo creado en la dirección :" & _

                    vbNewLine & _

                    sTempFile, _

                    MsgBoxStyle.Information, "Ruta del temporal")

            ' errores

        Catch ex As Exception

            MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)

        End Try

    End Sub

End Class

Leer todo el contenido de un archivo de texto en una sola operación y almacenarlo en una variable

Option Explicit On

Public Class Form1

    Private Sub Form1_Load( _

        ByVal sender As System.Object, _

        ByVal e As System.EventArgs) Handles MyBase.Load

        Try

            Dim SPath As String = "c:\un_archivo.txt"

            Dim sContent As String = vbNullString

            With My.Computer.FileSystem

                ' verifica si existe el path

                If .FileExists(SPath) Then

                    ' lee todo el contenido

                    sContent = .ReadAllText(SPath)

                    MsgBox(sContent.ToString, MsgBoxStyle.Information, "Datos")

                Else

                    MsgBox("ruta inválida", MsgBoxStyle.Critical, "error")

                End If

            End With

            ' errores

        Catch ex As Exception

            MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)

        End Try

    End Subd Class

Cargar directorios y archivos en un ListBox ( Métodos GetFiles y GetDirectories)

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

        ' Obtener todos los archivos .exe del directorio windows ( inclyendo subdirectorios )

        For Each archivos As String In Directory.GetFiles("c:\windows", _

                                                          "*.exe", _

                                                          SearchOption.AllDirectories)

            ' extraer el nombre de la ruta

            archivos = archivos.Substring(archivos.LastIndexOf("\") + 1).ToString

            ' Agregar el valor al listbox

            ListBox1.Items.Add(archivos.ToString)

        Next

        ' Obtener todos los directorios del directorio c: ( un solo nivel )

        For Each archivos As String In Directory.GetDirectories("c:\", "*.*", SearchOption.TopDirectoryOnly)

            ' extraer el nombre de la carpeta de la ruta completa

            archivos = archivos.Substring(archivos.LastIndexOf("\") + 1).ToString

            ' Agregar el valor

            ListBox2.Items.Add(archivos.ToString)

        Next

    End Sub

End Class

Obtener propiedades

Ejemplo que usa la clase FileInfo de system.IO para obtener algunas propiedades y datos de archivos ( el nombre , la fecha y la hora de modificación en formato corto , el tamaño en bytes y la extensión )

Colocar un control Listview, un button y un control TextBox

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

        ' agregar columnas

        With ListView1

            .Columns.Add("Nombre", 150)

            .Columns.Add("Fecha y hora de modificación", 150)

            .Columns.Add("Tamaño - bytes ", 100)

            .Columns.Add("Extensión", 80)

            .View = View.Details

            .GridLines = True

        End With

        Button1.Text = "Listar propiedades"

        TextBox1.Text = "c:\windows"

    End Sub

    Private Sub Button1_Click( _

        ByVal sender As System.Object, _

        ByVal e As System.EventArgs) Handles Button1.Click

        ListView1.Items.Clear()

        Try

            ' recorrer los ficheros en la colección

            For Each sFichero As String In Directory.GetFiles( _

                                           TextBox1.Text, "*.*", _

                                           SearchOption.TopDirectoryOnly)

                ' Crear nuevo objeto FileInfo

                Dim Archivo As New FileInfo(sFichero)

                ' Crear nuevo objeto ListViewItem

                Dim item As New ListViewItem(Archivo.Name.ToString)

                ' cargar los datos y las propiedades

                With item

                    ' LastWriteTime - fecha de modificación

                    .SubItems.Add(Archivo.LastWriteTime.ToShortDateString & " " & _

                                  Archivo.LastWriteTime.ToShortTimeString)

                    ' Length - tamaño en bytes

                    .SubItems.Add(Archivo.Length.ToString)

                    ' Extension - extensión  

                    .SubItems.Add(Archivo.Extension.ToString)

                    ListView1.Items.Add(item) ' añadir el item

                End With

            Next

            ' errores

        Catch ex As Exception

            Debug.Print(ex.Message.ToString)

            Beep()

        End Try

    End Sub

End Class

Información del sistema

Colocar un control listview en el formulario.

Option Explicit On

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) _

                           Handles MyBase.Load

        Try

            ' agrega dos encabezados

            With ListView1

                .Clear()

                .Columns.Add(" Información ", 350, HorizontalAlignment.Left)

                .Columns.Add(" Valor ", 200, HorizontalAlignment.Left)

                .View = View.Details

            End With

            ' agrega los items

            With My.Computer.Info

                ' Referencia al item

                Dim ObjItem As ListViewItem

                ' ram físca libre

                '''''''''''''''''''''''''''''''''''''''

                ObjItem = New ListViewItem("Memoria Física Disponible ")

                ObjItem.SubItems.Add(((.AvailablePhysicalMemory) / 1048576) & " MB")

                ListView1.Items.Add(ObjItem)

                ' Ram fisica total

                '''''''''''''''''''''''''''''''''''''''

                ObjItem = New ListViewItem("Memoria física total ")

                ObjItem.SubItems.Add(((.TotalPhysicalMemory) / 1048576) & " MB")

                ListView1.Items.Add(ObjItem)

                ' Ram Virtual libre

                '''''''''''''''''''''''''''''''''''''''

                ObjItem = New ListViewItem("Memoria Virtual libre")

                ObjItem.SubItems.Add(((.AvailableVirtualMemory) / 1048576) & " MB")

                ListView1.Items.Add(ObjItem)

                ' memoria virtual total

                '''''''''''''''''''''''''''''''''''''''

                ObjItem = New ListViewItem("Memoria virtual total")

                ObjItem.SubItems.Add(((.TotalVirtualMemory) / 1048576) & " MB")

                ListView1.Items.Add(ObjItem)

                ' Nombre del sistema operativo y la versión

                ''''''''''''''''''''''''''''''''''''''''''''''

                ObjItem = New ListViewItem("Sistema operativo - plataforma - versión")

                ObjItem.SubItems.Add(.OSFullName & "-" & .OSPlatform & "-" & .OSVersion).ToString()

                ListView1.Items.Add(ObjItem)

                ' autoajusta los headers

                ListView1.Columns(0).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

                ListView1.Columns(1).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

                ObjItem = Nothing

            End With

            ' error

        Catch omsg As Exception

            MsgBox(omsg.Message, MsgBoxStyle.Critical)

        End Try

    End Sub

End Class

Eliminar duplicados en un listbox o combobox

El ejemplo comienza comparando desde el primer item con todos los demás empezando desde abajo hacia arriba. Si el elemento es el mismo lo elimina con el método RemoveAt del ListBox indicando el índice

Colocar en el formulario

  • Un control ListBox llamado Listbox1
  • Un control Button llamado Button1

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, _

                           ByVal e As System.EventArgs) _

                           Handles MyBase.Load

        ' Agrega elementos , y algunos duplicados

        With ListBox1.Items

            .Add("1")

            .Add("2")

            .Add("3")

            .Add("1")

            .Add("2")

            .Add("3")

            ListBox1.SelectedIndex = 0

        End With

        Button1.Text = "Eliminar duplicados "

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _

                              ByVal e As System.EventArgs) _

                              Handles Button1.Click

        ' Le pasa el Listbox a la función

        MsgBox(Eliminar(ListBox1), _

               MsgBoxStyle.Information, _

               "Elementos duplicados en el List ")

    End Sub

    Function Eliminar(ByVal LB As ListBox) As Int32

        Dim i As Int32

        Dim j As Int32

        Dim n As Int32

        ' Recorre los items ( compara empezando _

        'desde el primero , de abajo hacia arriba)

        For i = 0 To LB.Items.Count - 2

            For j = LB.Items.Count - 1 To i + 1 Step -1

                ' ... si es el mismo

                If LB.Items(i).ToString = LB.Items(j).ToString Then

                    ' elimina el elemento indicando el índice

                    LB.Items.RemoveAt(j)

                    n += 1 'lleva la cuenta de los duplicados

                End If

            Next

        Next

        Return n ' retorna los eliminados

    End Function

End Class

 

http://www.recursosvisualbasic.com.ar/htm/vb-net/listado-1.htm

En construcción...