Menubar

viernes, 27 de octubre de 2017

Como crear un inputbox con opciones de lista desde vb.net

Por J. Manuel Mar H. Editar
Compartir en Facebook
Compartir en Twitter
Compartir en MeWe
Enviar a Reddit
Guardar en Internet archive
Guardar en  archive.today
Enviar por email
Inputbox Combobox  Desde VB.Net podemos usar, ya sea los controles nativos que nos provee el entorno de trabajo para enriquecer nuestra aplicación (desarrollar rápidamente). Esto nos permite usar componentes avanzados sin tener que programar nada (o muy poco), también podemos instalar librerías de terceros para extender la funcionalidad de nuestro programa, o bien crear nuestros propios controles y adaptarlos a nuestras necesidades. Hoy veremos como crear un control tipo InputBox pero con una lista desplegable desde la cual seleccionar una opción.
Publicidad


  El funcionamiento es muy simple: llamaremos a una función para mostrar el cuadro de diálogo, se le pasarán una serie de parámetros para personalizarlo (entre ellos la lista de opciones). El usuario seleccionará una opción de la lista y cuando presione el botón "Aceptar" de ese cuadro de diálogo se retornará el valor seleccionado, de lo contrario se devolverá una cadena de texto en blanco.
Veamos ahora su funcionamiento.

  Para empezar debemos desde nuestro código fuente llamar a la función que genera nuestro inputbox personalizado (un poco más adelante veremos su código fuente).

Dim user As String

user = drawComboInputBox("Seleccione un usuario de la lista:", list, "A123", "Ingresar al sistema")


If user.IsNullOrEmpty(user) = True Then

  MsgBox("No seleccionó ningún usuario")
Else
  MsgBox(user)
End If

  La función drawComboInputBox generará el inputbox con opciones de lista, el primer parámetro es el texto a mostrar dentro de la ventana, el segundo de ellos es un array con las opciones de la lista, el tercero de ellos la opción predeterminada (un texto) y el último de ellos el título de la ventana.

Si ejecutamos esa función, el resultado es el siguiente:
























  Este es el código fuente del control inputbox con lista de opciones, se encuentra dentro de una clase (frmComboInputBox), se llama a la misma desde una función para crear el diálogo (más abajo se muestra el código que genera la ventana). Por cierto, esta clase forma parte de una librería personal: Manuel's VB.Net Library, el código fuente de la misma se encuentra (no liberada la librería por falta de documentación interna) bajo licencia BSD/GPL, por lo que éste código fuente se puede usar libremente:


'Copyright (c) 2011, Juan Manuel Mar Hernández <marjuanm.dev@gmail.com>
'All rights reserved, BSD/GPL Dual License.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'- Redistributions of source code must retain the above copyright notice, this list 
'  of conditions and the following disclaimer.
'
'- Redistributions in binary form must reproduce the above copyright notice, this list
'  of conditions and the following disclaimer in the documentation and/or other materials 
'  provided with the distribution.
'
'- Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to 
'  endorse or promote products derived from this software without specific prior written 
'  permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS 
'OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
'AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
'CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
'DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
'DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
'IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
'OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'

' Creado por SharpDevelop.

' Usuario: 97016178
' Fecha: 11/07/2013
' Hora: 10:11 a.m.
'
' Para cambiar esta plantilla use Herramientas | Opciones | Codificación | Editar Encabezados Estándar

Public Partial Class frmComboInputBox


'#### Purpose: Initialize window
        '#### Created date: 11/10/2017
        '#### Created by username: Juan Manuel Mar Hdz.
        '#### Last modified date: 11/10/2017
        '#### Last modified username: Juan Manuel Mar Hdz.
Public Sub New()

' The Me.InitializeComponent call is required for Windows Forms designer support.
Me.InitializeComponent()

'
' TODO : Add constructor code after InitializeComponents
'
End Sub

'#### Purpose: Dispose class
        '#### Created date: 11/10/2017
        '#### Created by username: Juan Manuel Mar Hdz.
        '#### Last modified date: 11/10/2017
        '#### Last modified username: Juan Manuel Mar Hdz.
        '#### Thanks to http://www.vb-helper.com/howto_net_force_gc.html
        Protected Overrides Sub Finalize()
  MyBase.Finalize
        End Sub

'#### Purpose: Close window
        '#### Created date: 11/10/2017
        '#### Created by username: Juan Manuel Mar Hdz.
        '#### Last modified date: 11/10/2017
        '#### Last modified username: Juan Manuel Mar Hdz.
Sub CmdCancelClick(sender As Object, e As EventArgs)

GC.Collect
Me.Visible = False

End Sub

'#### Purpose: Close window and Return the string
        '#### Created date: 11/10/2017
        '#### Created by username: Juan Manuel Mar Hdz.
        '#### Last modified date: 11/10/2017
        '#### Last modified username: Juan Manuel Mar Hdz.
Sub CmdOKClick(sender As Object, e As EventArgs)

GC.Collect
Me.Visible = False

End Sub

'#### Purpose: Return text area
        '#### Created date: 11/10/2017
        '#### Created by username: Juan Manuel Mar Hdz.
        '#### Last modified date: 11/10/2017
        '#### Last modified username: Juan Manuel Mar Hdz.
        Public Function getText() As String
 
  If cboValue.Text.IsNullOrEmpty(cboValue.Text) = True Then
  Return ""
  Else
  Return cboValue.Text
  End If
 
       End Function
  
      '#### Purpose: Update message
      '#### Created date: 11/10/2017
      '#### Created by username: Juan Manuel Mar Hdz.
      '#### Last modified date: 11/10/2017
      '#### Last modified username: Juan Manuel Mar Hdz.
  Public Sub Update(message As String, items() As String, Optional defaultvalue As String = "", Optional title As String = "")

Dim i As Long

If title.IsNullOrEmpty(title) = False Then
  Me.Text = title.Trim
  Else
  Me.Text = ""
  End If
 
  cboValue.Items.Clear
 
  For i=0 To items.Length - 1

              If items(i).IsNullOrEmpty(items(i)) = False Then
  cboValue.Items.Add(items(i))
  End If
 
  Next
 
  If defaultvalue.IsNullOrEmpty(defaultvalue) = False Then
  cboValue.Text = defaultvalue.Trim
  Else
  cboValue.Text = ""
  End If
 
  If message.IsNullOrEmpty(message) = False Then
  lblMsg.Text = message.Trim
  Else
  lblMsg.Text = ""
  End If

  End Sub


'#### Purpose: Close window
        '#### Created date: 11/10/2017
        '#### Created by username: Juan Manuel Mar Hdz.
        '#### Last modified date: 11/10/2017
        '#### Last modified username: Juan Manuel Mar Hdz.
Sub frmComboInputBoxFormClosing(sender As Object, e As FormClosingEventArgs)

e.Cancel = False

GC.Collect
Me.Visible = False

End Sub
      End Class



Para llamar a la clase haremos uso de la siguiente función:

Private frmcombo As frmComboInputBox = Nothing
Private msgbutton As MsgBoxResult = Nothing

Public Function drawComboInputBox(message As String, list() As String, Optional defaulttext As String = "", Optional title As String = "") As String
 
  Dim mystr As String = ""

  If IsNothing(frmcombo) = True Then
      frmcombo = New frmComboInputBox()
  End If
 
  frmcombo.Update(message.Trim, list, defaulttext, title)
 
  Try
     msgbutton = frmcombo.ShowDialog
  Catch ex As Exception
        End Try

  If msgbutton = MsgBoxResult.Ok Then
     mystr = frmcombo.getText
  Else
     mystr = ""
  End If
 
        Try

frmcombo.Visible = False
    Return mystr

Catch exp As Exception
    Return ""
End Try

  End Function

  Como podemos ver, se llama a la clase que genera la ventana (por cierto hay que tener los archivos de la interfaz, se incluyen al final de este post) y se invoca al evento update, mediante el cual es posible personalizar la apariencia de la ventana y luego mediante el método getText obtenemos el valor seleccionado. Es todo, con ello ya tenemos un inputbox que muestra una lista de opciones.


¿Te gustó este post?, entonces si lo deseas puedes apoyarnos para continuar con nuestra labor, gracias.



Licencia de Creative Commons Esta obra está bajo una licencia de Creative Commons Reconocimiento 4.0 Internacional, haga clic aquí para conocer más detalles.


Compartir:



Danos tu voto
Comunidad Kynamio
Directorio de blogs, ¡agrega el tuyo!
Programas para el mantenimiento de Windows
Blog de seguridad informatica