Visual Basic .NET

Código de vb2Net en sus dos versiones:
Visual Basic 6.0 y Visual Basic .NET

Fecha: 26/Dic/2000



Nota: No se si el código lo publicaré "coloreado", en caso de no hacerlo, espero que no sea un inconveniente.


El código en VB6 (completo, incluyendo las definiciones de los controles, para que se vea la diferencia):

'
VERSION 5.00
Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "comdlg32.ocx"
Begin VB.Form fVB2NET 
   BorderStyle     =   1  'Fixed Single
   Caption         =   "Prueba para convertir a VB.NET"
   ClientHeight    =   5955
   ClientLeft      =   45
   ClientTop       =   330
   ClientWidth     =   6135
   LinkTopic       =   "Form1"
   LockControls    =   -1  'True
   MaxButton       =   0   'False
   OLEDropMode     =   1  'Manual
   ScaleHeight     =   5955
   ScaleWidth      =   6135
   StartUpPosition =   3  'Windows Default
   Begin MSComDlg.CommonDialog m_CD 
      Left            =   2670
      Top             =   4620
      _ExtentX        =   847
      _ExtentY        =   847
      _Version        =   393216
   End
   Begin VB.CommandButton cmdGuardar 
      Caption         =   "Leer..."
      Height          =   405
      Index           =   1
      Left            =   3390
      TabIndex        =   8
      ToolTipText     =   " Leer los datos de un fichero "
      Top             =   4620
      Width           =   1245
   End
   Begin VB.CommandButton cmdGuardar 
      Caption         =   "Guardar..."
      Height          =   405
      Index           =   0
      Left            =   4710
      TabIndex        =   9
      ToolTipText     =   " Guardar los datos en un fichero "
      Top             =   4620
      Width           =   1245
   End
   Begin VB.CommandButton cmdSalir 
      Cancel          =   -1  'True
      Caption         =   "Salir"
      Height          =   405
      Left            =   4710
      TabIndex        =   10
      ToolTipText     =   " Terminar el programa (ESC) "
      Top             =   5370
      Width           =   1245
   End
   Begin VB.CommandButton cmdAdd 
      Caption         =   "Añadir"
      Default         =   -1  'True
      Height          =   405
      Left            =   4710
      TabIndex        =   6
      ToolTipText     =   " Añadir los datos a la lista (INTRO) "
      Top             =   1410
      Width           =   1245
   End
   Begin VB.ListBox List1 
      BeginProperty Font 
         Name            =   "Courier New"
         Size            =   8.25
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Height          =   2580
      Left            =   180
      MultiSelect     =   2  'Extended
      OLEDropMode     =   1  'Manual
      TabIndex        =   7
      Top             =   1950
      Width           =   5745
   End
   Begin VB.TextBox Text1 
      Height          =   315
      Index           =   2
      Left            =   1590
      TabIndex        =   5
      Text            =   "Text1"
      Top             =   1020
      Width           =   4335
   End
   Begin VB.TextBox Text1 
      Height          =   315
      Index           =   1
      Left            =   1590
      TabIndex        =   3
      Text            =   "Text1"
      Top             =   630
      Width           =   4335
   End
   Begin VB.TextBox Text1 
      Height          =   315
      Index           =   0
      Left            =   1590
      TabIndex        =   1
      Text            =   "Text1"
      Top             =   240
      Width           =   4335
   End
   Begin VB.Line Line1 
      BorderColor     =   &H80000014&
      Index           =   1
      X1              =   120
      X2              =   6000
      Y1              =   5190
      Y2              =   5190
   End
   Begin VB.Line Line1 
      BorderColor     =   &H80000010&
      BorderWidth     =   2
      Index           =   0
      X1              =   120
      X2              =   6000
      Y1              =   5190
      Y2              =   5190
   End
   Begin VB.Label Label1 
      Caption         =   "Fecha nacimiento:"
      Height          =   255
      Index           =   2
      Left            =   180
      TabIndex        =   4
      Top             =   1050
      Width           =   1365
   End
   Begin VB.Label Label1 
      Caption         =   "E-mail:"
      Height          =   255
      Index           =   1
      Left            =   180
      TabIndex        =   2
      Top             =   660
      Width           =   1365
   End
   Begin VB.Label Label1 
      Caption         =   "Nombre:"
      Height          =   255
      Index           =   0
      Left            =   180
      TabIndex        =   0
      Top             =   270
      Width           =   1365
   End
End
Attribute VB_Name = "fVB2NET"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'------------------------------------------------------------------------------
' Prueba de formulario para convertir a VB.NET                      (24/Dic/00)
'
' ©Guillermo 'guille' Som, 2000
'
' Este proyecto contiene código "simple" para convertirlo a vb.net
'
' Se manejan ListBox, array de controles, el control de diálogos comunes
' controles del tipo Line,
' drag & drop en el formulario y en el ListBox,
' leer y grabar datos en ficheros de acceso aleatorio,
' tipos de datos definidos con cadenas de longitud fija
'------------------------------------------------------------------------------
Option Explicit

Private Type tColega
    Nombre As String * 50
    Email As String * 128
    FechaNac As String * 11 'dd/mm/yyyy
End Type

Private Sub cmdAdd_Click()
    ' Añadir los datos escritos al listbox
    With List1
        .AddItem Text1(0) & vbTab & Text1(1) & vbTab & Text1(2)
    End With
End Sub

Private Sub cmdGuardar_Click(Index As Integer)
    ' Leer o guardar, según el valor de Index
    On Error Resume Next
    
    With m_CD
        .CancelError = True
        .Filter = "Ficheros de texto (*.txt)|*.txt|Todos los ficheros (*.*)|*.*"
        .InitDir = App.Path
        .FileName = "Colegas.txt"
        If Index = 0 Then   ' Guardar
            .ShowSave
            If Err = 0 Then
                Guardar .FileName
            End If
        Else                ' Leer
            .ShowOpen
            If Err = 0 Then
                Leer .FileName
            End If
        End If
    End With
    Err = 0
End Sub

Private Sub cmdSalir_Click()
    Unload Me
End Sub

Private Sub Form_Load()
    '
    Dim i As Long
    
    ' Limpiar el contenido de los TextBoxes
    For i = 0 To 2
        Text1(i) = ""
    Next
    '
    ' Si no existe el fichero de ejemplo
    If Len(Dir$(App.Path & "\Colegas.txt")) = 0 Then
        ' Mostrar mis datos
        Text1(0) = "Guillermo"
        Text1(1) = "[email protected]"
        Text1(2) = "07/06/1957"
    End If
End Sub

Private Sub Guardar(ByVal sFic As String)
    ' Guardar el contenido del ListBox en el fichero indicado
    Dim i As Long, j As Long, n As Long
    Dim tmpColega As tColega
    Dim nFic As Long
    Dim s As String
    Dim d As String
    
    ' Si el nombre del fichero no es una cadena vacia
    If Len(sFic) Then
        On Error Resume Next
        '
        ' Si existe el fichero, borrarlo para que no acumule registros
        If Len(Dir$(sFic)) Then
            Kill sFic
        End If
        '
        ' Obtener un canal libre
        nFic = FreeFile
        '
        ' Abrir el fichero para grabar
        Open sFic For Random As nFic Len = Len(tmpColega)
        If Err = 0 Then
            ' Recorrer todos los elementos del ListBox
            For i = 0 To List1.ListCount - 1
                ' Cada uno de los elementos,
                ' se añade un vbTab para asegurarnos de que tenga uno al final
                s = List1.List(i) & vbTab
                ' son tres los datos en cada elemento del ListBox
                For n = 1 To 3
                    ' Buscar el primer vbTab
                    j = InStr(s, vbTab)
                    d = ""
                    ' Si hay alguno...
                    If j Then
                        d = Left$(s, j - 1)
                        s = Mid$(s, j + 1)
                    End If
                    ' Asignar el dato correspondiente
                    If n = 1 Then
                        tmpColega.Nombre = d
                    ElseIf n = 2 Then
                        tmpColega.Email = d
                    Else
                        tmpColega.FechaNac = d
                    End If
                Next
                Put #nFic, , tmpColega
            Next
            Close nFic
        Else
            Err = 0
        End If
    End If
End Sub

Private Sub Leer(ByVal sFic As String)
    ' Leer el contenido del ListBox en el fichero indicado
    Dim i As Long
    Dim n As Long
    Dim tmpColega As tColega
    Dim nFic As Long
    '
    ' Si el nombre del fichero no es una cadena vacia
    If Len(sFic) Then
        ' Borrar el contenido del ListBox
        List1.Clear
        ' Obtener un canal libre
        nFic = FreeFile
        '
        On Error Resume Next
        ' Abrir el fichero como acceso aleatorio
        Open sFic For Random As nFic Len = Len(tmpColega)
        If Err = 0 Then
            ' Asignar el número de registros del fichero
            n = LOF(nFic) \ Len(tmpColega)
            ' Recorrer todo el contenido del fichero
            For i = 1 To n
                Get #nFic, i, tmpColega
                ' Asignarlo al ListBox
                List1.AddItem Trim$(tmpColega.Nombre) & vbTab & Trim$(tmpColega.Email) & vbTab & Trim$(tmpColega.FechaNac)
            Next
            Close nFic
        Else
            Err = 0
        End If
    End If
End Sub

Private Sub Form_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)
    ' Leer el fichero
    Leer Data.Files(1)
End Sub

Private Sub List1_Click()
    ' Al pulsar en un elemento, mostrar los datos
    Dim s As String
    Dim d As String
    Dim i As Long
    Dim j As Long
    Dim n As Long
    
    i = List1.ListIndex
    If i > -1 Then
        s = List1.List(i) & vbTab
        For n = 0 To 2
            j = InStr(s, vbTab)
            d = ""
            If j Then
                d = Left$(s, j - 1)
                d = Trim$(d)
                s = Mid$(s, j + 1)
            End If
            Text1(n) = d
        Next
    End If
End Sub

Private Sub List1_KeyDown(KeyCode As Integer, Shift As Integer)
    ' Comprobar si se quiere borrar algún elemento
    If KeyCode = vbKeyDelete Then
        Dim i As Long
        '
        With List1
            ' Recorrer todos los elementos de atrás hacia adelante
            For i = .ListCount - 1 To 0 Step -1
                ' Si está seleccionado...
                If .Selected(i) Then
                    ' ...borrarlo
                    .RemoveItem i
                End If
            Next
        End With
    End If
End Sub

Private Sub List1_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)
    ' Leer el fichero soltado
    Leer Data.Files(1)
End Sub

Private Sub Text1_GotFocus(Index As Integer)
    ' Seleccionar el texto al entrar en el control
    With Text1(Index)
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
End Sub


El código en VB.NET (completo, incluyendo las definiciones de los controles)

'
'------------------------------------------------------------------------------
' Prueba de formulario para convertir a VB.NET                      (24/Dic/00)
' 
' ©Guillermo 'guille' Som, 2000
' 
' Este proyecto contiene código "simple" para convertirlo a vb.net
' 
' Se manejan ListBox, array de controles, el control de diálogos comunes
' controles del tipo Line,
' drag & drop en el formulario y en el ListBox,
' leer y grabar datos en ficheros de acceso aleatorio,
' tipos de datos definidos con cadenas de longitud fija
'------------------------------------------------------------------------------

Option Strict On
Option Explicit On
Imports VB = Microsoft.VisualBasic
Namespace tVB2NET
    Public Class fVB2NET
        Inherits System.WinForms.Form
        Private Shared m_vb6FormDefInstance As fVB2NET
        Public Shared Property DefInstance() As fVB2NET
            Get
                If m_vb6FormDefInstance Is Nothing Then
                    m_vb6FormDefInstance = New fVB2NET()
                End If
                DefInstance = m_vb6FormDefInstance
            End Get
            Set
                m_vb6FormDefInstance = Value
            End Set
        End Property

#Region " Windows Form Designer generated code "
        ' Required by the Win Form Designer
        Private components As System.ComponentModel.Container
        Public ToolTip1 As System.WinForms.ToolTip
        Public Tag1 As Microsoft.VisualBasic.Compatibility.VB6.Tag
        Private WithEvents fVB2NET As fVB2NET
        Public WithEvents m_CD As AxMSComDlg.AxCommonDialog
        Public WithEvents cmdGuardar_1 As System.WinForms.Button
        Public WithEvents cmdGuardar_0 As System.WinForms.Button
        Public WithEvents cmdSalir As System.WinForms.Button
        Public WithEvents cmdAdd As System.WinForms.Button
        Public WithEvents List1 As System.WinForms.ListBox
        Public WithEvents Text1_2 As System.WinForms.TextBox
        Public WithEvents Text1_1 As System.WinForms.TextBox
        Public WithEvents Text1_0 As System.WinForms.TextBox
        Public WithEvents Line1_1 As System.WinForms.Label
        Public WithEvents Line1_0 As System.WinForms.Label
        Public WithEvents Label1_2 As System.WinForms.Label
        Public WithEvents Label1_1 As System.WinForms.Label
        Public WithEvents Label1_0 As System.WinForms.Label
        Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
        Public WithEvents Line1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
        Public WithEvents Text1 As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
        Public WithEvents cmdGuardar As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray
        Public Sub New()
            MyBase.New()
            Me.fVB2NET = Me
            ' This call is required by the Win Form Designer
            If m_vb6FormDefInstance Is Nothing Then
                m_vb6FormDefInstance = Me
            End If
            InitializeComponent()
            Form_Load()
        End Sub
        ' Form overrides dispose to clean up the component list.
        Public Overrides Sub Dispose()
            MyBase.Dispose()
            components.Dispose()
        End Sub
        ' The main entry point for the application
        Shared Sub Main()
            System.WinForms.Application.Run(New fVB2NET())
        End Sub
        ' NOTE: The following procedure is required by the Win Form Designer
        ' It can be modified using the Win Form Designer.
        ' Do not modify it using the code editor.
        
        Private Sub InitializeComponent()
            Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(fVB2NET))
            
            Me.components = New System.ComponentModel.Container()
            Me.Text1_2 = New System.WinForms.TextBox()
            Me.cmdSalir = New System.WinForms.Button()
            Me.Text1_0 = New System.WinForms.TextBox()
            Me.cmdGuardar_0 = New System.WinForms.Button()
            Me.Text1_1 = New System.WinForms.TextBox()
            Me.cmdGuardar = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray()
            Me.m_CD = New AxMSComDlg.AxCommonDialog()
            Me.Line1_1 = New System.WinForms.Label()
            Me.cmdAdd = New System.WinForms.Button()
            Me.Line1_0 = New System.WinForms.Label()
            Me.cmdGuardar_1 = New System.WinForms.Button()
            Me.Label1_0 = New System.WinForms.Label()
            Me.Label1_1 = New System.WinForms.Label()
            Me.Label1_2 = New System.WinForms.Label()
            Me.Tag1 = New Microsoft.VisualBasic.Compatibility.VB6.Tag()
            Me.ToolTip1 = New System.WinForms.ToolTip(components)
            Me.Text1 = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray()
            Me.Line1 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray()
            Me.Label1 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray()
            Me.List1 = New System.WinForms.ListBox()
            
            m_CD.BeginInit()
            
            '@design Me.TrayHeight = 90
            '@design Me.TrayLargeIcon = False
            '@design Me.TrayAutoArrange = True
            Text1_2.Location = New System.Drawing.Point(106, 68)
            Text1_2.Cursor = System.Drawing.Cursors.Default
            Text1_2.Text = "Text1"
            Text1_2.RightToLeft = System.WinForms.RightToLeft.No
            Text1_2.AutoSize = False
            Text1_2.ForeColor = System.Drawing.SystemColors.WindowText
            Text1_2.TabIndex = 5
            Text1.SetIndex(Text1_2, 2%)
            Text1_2.Size = New System.Drawing.Size(289, 21)
            Text1_2.BackColor = System.Drawing.SystemColors.Window
            
            cmdSalir.Location = New System.Drawing.Point(314, 358)
            cmdSalir.BackColor = System.Drawing.SystemColors.Control
            ToolTip1.SetToolTip(cmdSalir, " Terminar el programa (ESC) ")
            cmdSalir.DialogResult = System.WinForms.DialogResult.Cancel
            cmdSalir.Size = New System.Drawing.Size(83, 27)
            cmdSalir.TabIndex = 10
            cmdSalir.RightToLeft = System.WinForms.RightToLeft.No
            cmdSalir.Text = "Salir"
            
            Text1_0.Location = New System.Drawing.Point(106, 16)
            Text1_0.Cursor = System.Drawing.Cursors.Default
            Text1_0.Text = "Text1"
            Text1_0.RightToLeft = System.WinForms.RightToLeft.No
            Text1_0.AutoSize = False
            Text1_0.ForeColor = System.Drawing.SystemColors.WindowText
            Text1_0.TabIndex = 1
            Text1.SetIndex(Text1_0, 0%)
            Text1_0.Size = New System.Drawing.Size(289, 21)
            Text1_0.BackColor = System.Drawing.SystemColors.Window
            
            cmdGuardar_0.Location = New System.Drawing.Point(314, 308)
            cmdGuardar_0.Text = "Guardar..."
            cmdGuardar_0.Size = New System.Drawing.Size(83, 27)
            cmdGuardar_0.RightToLeft = System.WinForms.RightToLeft.No
            ToolTip1.SetToolTip(cmdGuardar_0, " Guardar los datos en un fichero ")
            cmdGuardar_0.TabIndex = 9
            cmdGuardar.SetIndex(cmdGuardar_0, 0%)
            cmdGuardar_0.BackColor = System.Drawing.SystemColors.Control
            
            Text1_1.Location = New System.Drawing.Point(106, 42)
            Text1_1.Cursor = System.Drawing.Cursors.Default
            Text1_1.Text = "Text1"
            Text1_1.RightToLeft = System.WinForms.RightToLeft.No
            Text1_1.AutoSize = False
            Text1_1.ForeColor = System.Drawing.SystemColors.WindowText
            Text1_1.TabIndex = 3
            Text1.SetIndex(Text1_1, 1%)
            Text1_1.Size = New System.Drawing.Size(289, 21)
            Text1_1.BackColor = System.Drawing.SystemColors.Window
            
            '@design cmdGuardar.SetLocation(New System.Drawing.Point(363, 7))
            
            m_CD.Size = New System.Drawing.Size(32, 32)
            m_CD.OcxState = CType(resources.GetObject("m_CD.OcxState"), System.WinForms.AxHost.State)
            m_CD.TabIndex = 0
            m_CD.Location = New System.Drawing.Point(178, 308)
            
            Line1_1.Location = New System.Drawing.Point(8, 346)
            Line1_1.Size = New System.Drawing.Size(392, 2)
            Line1_1.TabIndex = 11
            Line1.SetIndex(Line1_1, 1%)
            Line1_1.BackColor = System.Drawing.SystemColors.HighlightText
            
            cmdAdd.Location = New System.Drawing.Point(314, 94)
            cmdAdd.BackColor = System.Drawing.SystemColors.Control
            ToolTip1.SetToolTip(cmdAdd, " Añadir los datos a la lista (INTRO) ")
            cmdAdd.Size = New System.Drawing.Size(83, 27)
            cmdAdd.TabIndex = 6
            cmdAdd.RightToLeft = System.WinForms.RightToLeft.No
            cmdAdd.Text = "Añadir"
            
            Line1_0.Location = New System.Drawing.Point(8, 346)
            Line1_0.Size = New System.Drawing.Size(392, 1)
            Line1_0.TabIndex = 12
            Line1.SetIndex(Line1_0, 0%)
            Line1_0.BackColor = System.Drawing.SystemColors.ControlDark
            
            cmdGuardar_1.Location = New System.Drawing.Point(226, 308)
            cmdGuardar_1.Text = "Leer..."
            cmdGuardar_1.Size = New System.Drawing.Size(83, 27)
            cmdGuardar_1.RightToLeft = System.WinForms.RightToLeft.No
            ToolTip1.SetToolTip(cmdGuardar_1, " Leer los datos de un fichero ")
            cmdGuardar_1.TabIndex = 8
            cmdGuardar.SetIndex(cmdGuardar_1, 1%)
            cmdGuardar_1.BackColor = System.Drawing.SystemColors.Control
            
            Label1_0.Location = New System.Drawing.Point(8, 18)
            Label1_0.Text = "Nombre:"
            Label1_0.Size = New System.Drawing.Size(96, 17)
            Label1_0.RightToLeft = System.WinForms.RightToLeft.No
            Label1_0.ForeColor = System.Drawing.SystemColors.ControlText
            Label1_0.TabIndex = 0
            Line1.SetIndex(Label1_0, 0%)
            Label1_0.BackColor = System.Drawing.SystemColors.Control
            Label1_0.TextAlign = System.WinForms.HorizontalAlignment.Right
            
            Label1_1.Location = New System.Drawing.Point(8, 44)
            Label1_1.Text = "E-mail:"
            Label1_1.Size = New System.Drawing.Size(96, 17)
            Label1_1.RightToLeft = System.WinForms.RightToLeft.No
            Label1_1.ForeColor = System.Drawing.SystemColors.ControlText
            Label1_1.TabIndex = 2
            Line1.SetIndex(Label1_1, 1%)
            Label1_1.BackColor = System.Drawing.SystemColors.Control
            Label1_1.TextAlign = System.WinForms.HorizontalAlignment.Right
            
            Label1_2.Location = New System.Drawing.Point(8, 70)
            Label1_2.Text = "Fecha nacimiento:"
            Label1_2.Size = New System.Drawing.Size(96, 17)
            Label1_2.RightToLeft = System.WinForms.RightToLeft.No
            Label1_2.ForeColor = System.Drawing.SystemColors.ControlText
            Label1_2.TabIndex = 4
            Line1.SetIndex(Label1_2, 2%)
            Label1_2.BackColor = System.Drawing.SystemColors.Control
            Label1_2.TextAlign = System.WinForms.HorizontalAlignment.Right
            
            '@design Tag1.SetLocation(New System.Drawing.Point(90, 7))
            
            '@design ToolTip1.SetLocation(New System.Drawing.Point(7, 7))
            ToolTip1.Active = True
            
            '@design Text1.SetLocation(New System.Drawing.Point(295, 7))
            
            '@design Line1.SetLocation(New System.Drawing.Point(228, 7))
            
            '@design Label1.SetLocation(New System.Drawing.Point(155, 7))
            
            List1.Location = New System.Drawing.Point(12, 130)
            List1.SelectionMode = System.WinForms.SelectionMode.MultiExtended
            List1.Size = New System.Drawing.Size(383, 172)
            List1.RightToLeft = System.WinForms.RightToLeft.No
            List1.Font = New System.Drawing.Font("Courier New", 8.25!)
            List1.TabIndex = 7
            
            Me.Location = New System.Drawing.Point(3, 22)
            Me.Text = "Prueba para convertir a VB.NET"
            Me.MaximizeBox = False
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.CancelButton = cmdSalir
            Me.BorderStyle = System.WinForms.FormBorderStyle.FixedSingle
            Me.AcceptButton = cmdAdd
            Me.ClientSize = New System.Drawing.Size(409, 397)
            
            Me.Controls.Add(m_CD)
            Me.Controls.Add(cmdGuardar_1)
            Me.Controls.Add(cmdGuardar_0)
            Me.Controls.Add(cmdSalir)
            Me.Controls.Add(cmdAdd)
            Me.Controls.Add(List1)
            Me.Controls.Add(Text1_2)
            Me.Controls.Add(Text1_1)
            Me.Controls.Add(Text1_0)
            Me.Controls.Add(Line1_0)
            Me.Controls.Add(Label1_2)
            Me.Controls.Add(Label1_1)
            Me.Controls.Add(Label1_0)
            Me.Controls.Add(Line1_1)
            
            m_CD.EndInit()
        End Sub
#End Region
        
        'Private Structure tColega
        '    Dim Nombre As String
        '    Dim Email As String
        '    Dim FechaNac As String
        'End Structure
        Private Structure tColega
            ' Variables privadas para almacenar los valores de las propiedades
            Private _Nombre As String
            Private Const LenNombre As Integer = 50
            Private _Email As String
            Private Const LenEmail As Integer = 128
            Private _FechaNac As String
            Private Const LenFechaNac As Integer = 11
            '
            ' Esta función devolverá una cadena con el tamaño indicado
            Private Function ProperLen(ByVal sElement As String, ByVal nLen As Integer) As String
                Return VB.Left(sElement & Space(nLen), nLen)
            End Function
            '
            ' Propiedades públicas,
            ' se devuelve y asigna el tamaño que queramos que tengan
            Property Nombre() As String
                Get
                    Return ProperLen(_Nombre, LenNombre)
                End Get
                Set
                    _Nombre = ProperLen(Value, LenNombre)
                End Set
            End Property
            Property Email() As String
                Get
                    Return ProperLen(_Email, LenEmail)
                End Get
                Set
                    _Email = ProperLen(Value, LenEmail)
                End Set
            End Property
            Property FechaNac() As String
                Get
                    Return ProperLen(_FechaNac, LenFechaNac)
                End Get
                Set
                    _FechaNac = ProperLen(Value, LenFechaNac)
                End Set
            End Property
            ' Len devolverá el tamaño total que queremos que tenga
            Function Len() As Integer
                Return LenNombre + LenEmail + LenFechaNac
            End Function
            ' Put devolverá el contenido de la estructura
            ' con el tamaño adecuado para cada uno de los elementos
            ' de la estructura.
            Function Put() As String
                Return Nombre & Email & FechaNac
            End Function
            ' Esta propiedad recibirá una cadena
            ' y la desglosará en cada uno de los campos
            ' El Get hay que ponerlo entre corchetes para indicarle
            ' que es un nombre de propiedad.
            WriteOnly Property [Get]() As String
                Set
                    Dim s As String
                    s = ProperLen(Value, Me.Len())
                    Nombre = VB.Left(s, LenNombre)
                    Email = Mid(s, LenNombre + 1, LenEmail)
                    FechaNac = VB.Right(s, LenFechaNac)
                End Set
            End Property
        End Structure
        
        Private Sub Guardar(ByVal sFic As String)
            ' Guardar el contenido del ListBox en el fichero indicado
            Dim j, i, n As Integer
            Dim tmpColega As tColega
            Dim nFic As Integer
            Dim s As String
            Dim d As String
            
            ' Si el nombre del fichero no es una cadena vacia
            If CBool(Len(sFic)) Then
                On Error Resume Next
                '
                ' Si existe el fichero, borrarlo
                If CBool(Len(Dir(sFic))) Then
                    VB.Kill(sFic)
                End If
                '
                Err.Number = 0
                '
                ' Obtener un canal libre
                nFic = VB6.FreeFile
                ' 
                ' Abrir el fichero para grabar
                'VB6.Open(nFic, sFic, VB6.OpenMode.Random, , , System.Runtime.InteropServices.Marshal.SizeOf(tmpColega))
                'VB6.Open(nFic, sFic, VB6.OpenMode.Random, , , SizeOf(tmpColega))
                VB6.Open(nFic, sFic, VB6.OpenMode.Binary)
                If Err.Number = 0 Then
                    ' Recorrer todos los elementos del ListBox
                    For i = 0 To List1.Items.Count - 1
                        ' Se añade un vbTab para asegurarnos de que tenga uno al final
                        's = VB6.GetItemString(List1, i) & ControlChars.Tab
                        ' Esto también se puede hacer de esta otra forma:
                        s = List1.Items(i).ToString & ControlChars.Tab
                        ' son tres los datos en cada elemento del ListBox
                        For n = 1 To 3
                            ' Buscar el primer vbTab
                            j = InStr(s, ControlChars.Tab)
                            d = ""
                            ' Si hay alguno...
                            If CBool(j) Then
                                'd = VB6.GetDefaultProperty(VB.Left(s, j - 1))
                                d = VB.Left(s, j - 1)
                                s = Mid(s, j + 1)
                            End If
                            ' Asignar el dato correspondiente
                            If n = 1 Then
                                tmpColega.Nombre = d
                            ElseIf n = 2 Then
                                tmpColega.Email = d
                            Else
                                tmpColega.FechaNac = d
                            End If
                        Next
                        'VB6.FilePut(nFic, tmpColega)
                        VB6.FilePut(nFic, tmpColega.Put())
                    Next
                    VB6.Close(nFic)
                Else
                    Err.Clear()
                End If
            End If
        End Sub
        
        Private Sub Leer(ByVal sFic As String)
            ' Leer el contenido del ListBox en el fichero indicado
            Dim i As Integer
            Dim n As Integer
            Dim tmpColega As tColega
            Dim nFic As Integer
            Dim s As String
            ' 
            ' Si el nombre del fichero no es una cadena vacia
            If CBool(Len(sFic)) Then
                ' Borrar el contenido del ListBox
                List1.Items.Clear()
                ' Obtener un canal libre
                nFic = VB6.FreeFile
                ' 
                On Error Resume Next
                ' Abrir el fichero como acceso aleatorio
                'VB6.Open(nFic, sFic, VB6.OpenMode.Random, , , System.Runtime.InteropServices.Marshal.SizeOf(tmpColega))
                'VB6.Open(nFic, sFic, VB6.OpenMode.Random, , , SizeOf(tmpColega))
                VB6.Open(nFic, sFic, VB6.OpenMode.Binary)
                If Err.Number = 0 Then
                    ' Asignar el número de registros del fichero
                    'n = VB6.LOF(nFic) \ System.Runtime.InteropServices.Marshal.SizeOf(tmpColega)
                    n = VB6.LOF(nFic).ToInt16 \ tmpColega.Len()
                    ' Recorrer todo el contenido del fichero
                    s = Space(tmpColega.Len())
                    For i = 1 To n
                        'VB6.FileGet(nFic, tmpColega, i)
                        VB6.FileGet(nFic, s)
                        tmpColega.Get = s
                        ' Asignarlo al ListBox
                        List1.Items.Add(Trim(tmpColega.Nombre) & ControlChars.Tab & Trim(tmpColega.Email) & ControlChars.Tab & Trim(tmpColega.FechaNac))
                    Next
                    VB6.Close(nFic)
                Else
                    Err.Clear()
                End If
            End If
        End Sub
        
        Private Sub cmdAdd_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
            ' Añadir los datos escritos al listbox
            With List1
                .Items.Add(Text1.Item(0).Text & ControlChars.Tab & Text1.Item(1).Text & ControlChars.Tab & Text1.Item(2).Text)
            End With
        End Sub
        
        Private Sub cmdGuardar_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
            Dim Index As Short
            Index = cmdGuardar.GetIndex(CType(eventSender, System.WinForms.Button))
            ' Leer o guardar, según el valor de Index
            On Error Resume Next
            
            With m_CD
                .CancelError = True
                .Filter = "Ficheros de texto (*.txt)|*.txt|Todos los ficheros (*.*)|*.*"
                .InitDir = System.WinForms.Application.StartUpPath
                .FileName = "Colegas.txt"
                If Index = 0 Then '  Guardar
                    .ShowSave()
                    If Err.Number = 0 Then
                        Guardar(.FileName)
                    End If
                Else
                    .ShowOpen()
                    If Err.Number = 0 Then
                        Leer(.FileName)
                    End If
                End If
            End With
            Err.Clear()
        End Sub
        
        Private Sub cmdSalir_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
            Me.Close()
        End Sub
        
        Private Sub Form_Load()
            ' 
            Dim i As Short 'Integer
            
            ' Limpiar el contenido de los TextBoxes
            For i = 0 To 2
                Text1.Item(i).Text = ""
            Next
            ' 
            ' Si no existe el fichero de ejemplo
            If Len(Dir(System.WinForms.Application.StartUpPath & "\Colegas.txt")) = 0 Then
                ' Mostrar mis datos
                Text1.Item(0).Text = "Guillermo"
                Text1.Item(1).Text = "[email protected]"
                Text1.Item(2).Text = "07/06/1957"
            End If
        End Sub
        
        ''UPGRADE_WARNING: Ole Drag drop cannot be migrated to VB7
        'Private Sub Form_OLEDragDrop(ByRef Data As DataObject, ByRef Effect As Integer, ByRef Button As Short, ByRef Shift As Short, ByRef X As Single, ByRef Y As Single)
        '	' Leer el fichero
        '	Leer(Data.Files(1))
        'End Sub
        
        Private Sub List1_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
            ' Al pulsar en un elemento, mostrar los datos
            Dim s As String
            Dim d As String
            Dim i As Integer
            Dim j As Integer
            Dim n As Short 'Integer
            
            i = List1.SelectedIndex
            If i > -1 Then
                's = VB6.GetItemString(List1, i) & ControlChars.Tab
                s = List1.Items(i).ToString & ControlChars.Tab
                For n = 0 To 2
                    j = InStr(s, ControlChars.Tab)
                    d = ""
                    If CBool(j) Then
                        'd = VB6.GetDefaultProperty(VB.Left(s, j - 1))
                        d = VB.Left(s, j - 1)
                        d = Trim(d)
                        s = Mid(s, j + 1)
                    End If
                    Text1.Item(n).Text = d
                Next
            End If
        End Sub
        
        Private Sub List1_KeyDown(ByVal eventSender As System.Object, ByVal eventArgs As System.WinForms.KeyEventArgs)
            Dim KeyCode As Short = eventArgs.KeyCode.ToInt16  ' Convert from Keys to VB6.ShiftConstants
            Dim Shift As Short = (eventArgs.KeyData \ &H10000).ToInt16
            ' Comprobar si se quiere borrar algún elemento
            Dim i As Integer
            If KeyCode = System.WinForms.Keys.Delete Then
                ' 
                With List1
                    ' Recorrer todos los elementos de atrás hacia adelante
                    For i = .Items.Count - 1 To 0 Step -1
                        ' Si está seleccionado...
                        If .GetSelected(i) Then
                            ' ...borrarlo
                            .Items.Remove(i)
                        End If
                    Next
                End With
            End If
        End Sub
        
        ''UPGRADE_WARNING: Ole Drag drop cannot be migrated to VB7
        'Private Sub List1_OLEDragDrop(ByRef Data As DataObject, ByRef Effect As Integer, ByRef Button As Short, ByRef Shift As Short, ByRef X As Single, ByRef Y As Single)
        '	' Leer el fichero soltado
        '	Leer(Data.Files(1))
        'End Sub
        
        Private Sub Text1_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
            Dim Index As Short
            Index = Text1.GetIndex(CType(eventSender, System.Winforms.TextBox))
            ' Seleccionar el texto al entrar en el control
            With Text1.Item(Index)
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With
        End Sub
    End Class
End Namespace

Volver a la página explicativa

Ir al índice de vb.net

la Luna del Guille o... el Guille que está en la Luna... tanto monta...