Uso del control ComboBox

Escrito por Carla Vázquez el Martes 19 de Febrero de 2008 a las 15:40hs

El control Combobox de Visual Basic es uno de los recursos m?s utilizados a la hora de programar. Su comportamiento es similar al control Listbox, s?lo que a diferencia de este ?ltimo, el control Combobox no s?lo permite la selecci?n de una opci?n dentro de una lista predefinida de datos, sino adem?s ingresar una nueva entrada.

Por lo tanto, esta herramienta resulta fundamental a la hora de definir aquel conjunto de datos. El Combobox consta de dos partes: un encabezado que corresponde al nombre de dicho conjunto (por ejemplo: Pa?ses o Sexo) y una segunda que abarca las opciones posibles (ejemplo: masculino, femenino), es decir comprende una lista de elementos que delimitan la selecci?n del usuario. Este control cuenta con diferentes estilos o modos. El primero es una forma Simple que muestra el control Edit y el ListBox.

Gracias a la propiedad DropDownStyle, otra forma permite el despliegue de la lista hacia abajo. En principio la lista permanece oculta, mostr?ndose ?nicamente cuando el usuario presione el icono de la flecha a la derecha del control. Por lo tanto dependiendo del estilo que se utilice estar? abierta la posibilidad o no para editar el campo de selecci?n. La lista de opciones o respuestas se carga al mismo momento de dise?o de la ventana.

Para llevar a cabo dicha aplicaci?n se deber? ingresar en la p?gina de propiedades y all? proceder a ingresar la primera opci?n o respuesta y aceptar (enter). Esta acci?n debe repetirse para cargar todas las respuestas deseadas, siendo conveniente en el caso de tratarse de un n?mero reducido de opciones. El Combobox contiene una serie de propiedades aplicables ?nicamente en tiempo de ejecuci?n, siendo las principales:

  • ListCount: sirve para indicar el n?mero de elementos en la lista correspondiente
  • ListIndex: proporciona el n?mero de orden del elemento que se ha seleccionado; AddItem y RemoveItem permite agregar o eliminar elementos.
  • List (n): obtiene el elemento cuyo n?mero de orden est? indicado con ?n?.
  • Text: consiste en una propiedad que muestra el texto de la parte Textbox del Combobox, la cual puede introducirse a trav?s del teclado o ser una opci?n seleccionada, como vimos anteriormente.

Datos ?tiles para programar en Visual Basic:

Valor Seleccionado:

Combo.ItemData(Combo.ListIndex)

A la hora de agregar datos, se utiliza la funci?n Add

Combo.AddItem "Primera Hoja" Combo.ItemData(0) = 1234 Combo.AddItem "Segunda Hoja" Combo.ItemData(1) = 5678

En el caso de querer eliminar elementos, la funci?n requerida es la siguiente:

1) Para eliminar un elemento con el ?ndice cero:

ComboBox1.Items.RemoveAt(0)

2) Para eliminar un elemento actualmente seleccionado:

ComboBox1.Items.Remove(ComboBox1.SelectedItem)

3) Para eliminar el elemento "ejemplo":

ComboBox1.Items.Remove("ejemplo")

4) En caso de optar por eliminar todos los elementos:

ListBox1.Items.Clear()

Otra opci?n que brinda el recurso Combobox es permitir ordenar los elementos de la lista correspondiente, dado que no los ordena por s? solo. Por lo tanto, en caso de desear una visualizaci?n alfab?ticamente ordenada se debe establecer en la propiedad ?sorted? (de la ventana propiedades) el valor ?true?. ?De este modo los elementos quedar?n en orden!

Espero les haya servido de ayuda!


comentarios



  1. Hola, me encuentro programando en Visual Basic .NET y access, soy nuevo en esto de programar, mi pregunta es la siguiente:

    En mi combo traigo tres campos de una tabla de mi base de datos, cundo yo selecciono algun registro de mi combo, quiero que me traiga en un datagridview los datos que corresponder al registro seleccionado.

    Cuando solo traigo un registro en mi combo (nombre) si me funciona.

    Pero yo lo quiero hacer con tres registros de mi combo (nombre, marca, presentacion).



  2. Hola... Estoy iniciando en programación y específicamente en VB porque me han sugerido que es muy bueno...
    Tengo un combobox el cual lleva una lista de elementos de texto y quiero que cuando seleccione uno de ellos me muestre en un label... Por ejemplo:
    -Tengo en la lista del combobox las siguientes opciones:
    Nombre
    Sexo
    Empleo
    -Quiero que cuando seleccione Nombre, me muestre en un label:
    Juan Pérez
    Pedro Gonzñalez
    -Quiero que cuando seleccione Sexo, me muestre en un label:
    Masculino
    Femenino
    -Quiero que cuando seleccione Empleo, me muestre en un label:
    Mecánico
    Albañil
    Plomero
    ¿Se entiende? Gracias...



  3. bueno yo quisiera llevar todo lo que contiene un listbox a un combobox

    todos los elementos me gustaria saber como se hace



  4. hola ..!!
    mi problema es que estoy trabajando una conexion visual basic con acces y agrege una opcion llamada codigo(un combo box) en la cual me desplega la lista de codigos existentes pero quiero que a la hora de que no exista alguno agregarlo en ese mismo combo box ya consegui que lo guarde en la base de datos de acces pero no consigo que quede en el combo box como ago eso.....????? porfa si me responden estare muy agradecido



  5. ola quetal--bueno lo que quireo es seleccionar los elementos de un combo y me muestre en listbox



  6. la verdad es q necesito ayuda estoy trabajando con visual basic 2008 express y la verdad es q no se como utilizarlo a mi el maestro me da codig de visual basic 6 y no como hacerle para convertir ciertas funciones a otras como el additem

    si me pudieran contestar se los agradeceria mucho



  7. estoy trabajando con visual basic version 6 pero no entiendo nada nececito ayuda
    como por ejemplo para hacer una calculadora y eso



  8. menudos pringaos



  9. en un formulario tengo un textbox, un combobox, y un command button.
    ok.

    kiero que al darle un click al boton, el dato que tenga en el textbox lo mande al combobox. y viceversa. es en visual basic 6.0 ¡alguien puede ayudarme?
    Gracias.



  10. HOLA A TODOS ........... TENGO QUE HACER UN EJEMPLO DE UN PROGRAMA EL CUAL HAGA LO SIGUIENTE,,,,,,,,,,,,,,

    QUE DESDE UN COMBOBOX AL SELECCIONAR UNA OPCION ME DESPLIEGUE LOS DATOS EN UN DATAGRIDVIEW, POR MAS QUE BUSCADO NO ENCUENTRO ALGO SIMILAR A LO QUE NECESITO.

    ES QUE EN MI TABLA TENGO REPITIDO LA INFORMACION DEL CAMPO Y POR ESO LOS QUIERO AGRUPAR POR "CAMPO" Y MOSTRARLOS EN UN COMBO Y ASI AL MOMENTO DE SELECCIONAR ME TRAIGA TODA LA INFORMACION DE LO QUE CONTIENE EL" CAMPO"



    AYUDA

    GRACIAS DE ANTEMANO



  11. se me olvidaba estoy trabajando con visual basic 2005 y sql server 2005

    cualquier ayuda informarme en mi correo por favor



  12. Bueno, estoy haciendo un trabajo en Visual Basic 6.0,
    tengo un problemilla con el combobox,...enlace a la lista de este unos datos de una base de datos...y hago que al elegir uno,se vaya a un text, pero al momento de grabar graba todo menos lo que envie del combobox,...ademas me gustaria que al elegir una carrera en el siguiente combo aparescan todas las asignaturas correspondientes a esa carrera,..de todas maneras te envio el codigo form load:

    Private Sub cmdEliminar_Click()
    If MsgBox("confirme", vbYesNo + vbQuestion, "Desea Eliminar Registro") = vbYes Then
    Data_Doc.Recordset.Delete
    Data_Doc.Recordset.MoveFirst
    Do While Not Data_Doc.Recordset.EOF
    If Data_Doc.Recordset("Rut") = txtRut.Text Then
    Data_Doc.Recordset.Delete
    End If
    Data_Doc.Recordset.MoveNext
    Loop
    Data_Doc.Refresh
    Limpiar
    End If
    End Sub

    Private Sub cmdGuardar_Click()
    If MsgBox("Confirme", 4 + 32, "Desea Guardar Docente") = 6 Then
    Data_Doc.Recordset.AddNew
    Data_Doc.Recordset("Rut") = txtRut.Text
    Data_Doc.Recordset("Nombre") = txtNombre.Text
    Data_Doc.Recordset("NomCarrera") = txtNomCarrera.Text
    Data_Doc.Recordset("NomAsig") = txtAsig.tet
    Data_Doc.Recordset("HoraSema") = txtHoraSema.Text
    Data_Doc.Recordset("HoraSeme") = txtHoraSeme.Text
    Data_Doc.Recordset("HoraRealsem") = txtHoraReal.Text
    Data_Doc.Recordset("DifHora") = txtDifHoras.Text
    Data_Doc.Recordset("Jornada") = txtJornada.Text
    Data_Doc.Recordset.Update
    Else
    txtRut.Text = ""
    txtNombre.Text = ""
    txtCarre.Text = ""
    txtAsig.Text = ""
    txtHoraSema.Text = ""
    txtHoraSeme.Text = ""
    txtHoraReal.Text = ""
    txtDifHoras.Text = ""
    txtJornada.Text = ""
    End If
    cmdGuardar.Enabled = False
    Limpiar
    txtRut.SetFocus
    End Sub

    Private Sub cmdLimpiar_Click()
    msg = MsgBox("Se limpiaran ambas fechas.¿Desea Limpiar las Fecchas?", vbOKCancel, "Atención")
    Limpiar
    End Sub
    Private Function Limpiar()
    If msg = vbOK Then
    txtFechIni = ""
    txtFechTerm = ""
    txtRut = ""
    txtNombre = ""
    txtCarre = ""
    txtAsig = ""
    Combo1 = ""
    Combo2 = ""
    txtHoraSema = ""
    txtHoraSeme = ""
    txtHoraReal = ""
    txtDifHoras = ""
    txtJornada = ""
    txtFechIni.SetFocus
    Else
    txtRut = ""
    txtNombre = ""
    txtCarre = ""
    txtAsig = ""
    txtHoraSema = ""
    txtHoraSeme = ""
    txtHoraReal = ""
    txtDifHoras = ""
    txtJornada = ""
    txtRut.Enabled = True
    txtRut.SetFocus
    End If
    End Function
    Private Function vrut(txtRut)
    l = Len(txtRut) - 2
    s = 0
    m = 2
    For i = l To 1 Step -1
    c = Mid(txtRut, i, 1)
    s = s + Val(c) * m
    m = m + 1
    If m = 8 Then
    m = 2
    End If
    Next i
    RESTO = s Mod 11
    DV = 11 - RESTO
    If DV = 10 Then
    DVc = "k"
    End If
    If DV = 11 Then
    DVc = "0"
    End If
    If DV 10 And DV 11 Then
    DVc = CStr(DV)
    DVc = Right(DVc, 1)
    End If
    If DVc = Right(txtRut, 1) Then
    txtNombre.Enabled = True
    txtNombre.SetFocus

    Else
    a = MsgBox("Rut erroneo", vbOKOnly, "Error!!")
    txtRut = ""
    End If
    End Function

    Private Sub cmdModificar_Click()
    txtRut.Enabled = True
    txtNombre.Enabled = True
    txtCarre.Enabled = True
    txtAsig.Enabled = True
    txtHoraSema.Enabled = True
    txtHoraSeme.Enabled = True
    txtHoraReal.Enabled = True
    txtDifHoras.Enabled = True
    txtJornada.Enabled = True
    cmdGuardar.Enabled = True
    cmdEliminar.Enabled = True
    Data_Doc.Recordset.Edit
    End Sub

    Private Sub cmdNuevo_Click()
    Data_Doc.Refresh
    Data_Doc.Recordset.AddNew

    txtRut = ""
    txtNombre = ""
    txtCarre = ""
    txtAsig = ""
    txtHoraSema = ""
    txtHoraSeme = ""
    txthorarealseme = ""
    txtDifHoras = ""
    txtJornada = ""
    txtRut.Enabled = True
    txtRut.SetFocus
    End Sub

    Private Sub Combo1_Click()
    Dim Carrera As String
    Carrera = Combo1.Text
    txtCarre = Carrera
    txtCarre.Enabled = False
    Combo2.Enabled = True
    Combo2.SetFocus

    End Sub

    Private Sub Combo2_Click()
    Dim asig As String
    asig = Combo2.Text
    txtAsig = asig
    txtAsig.Enabled = False
    txtHoraSema.Enabled = True
    txtHoraSema.SetFocus
    End Sub


    Private Sub Form_Load()
    Flash1.Movie = (App.Path & "arriba.swf")
    Data_Doc.RecordsetType = 0
    Data_Doc.DatabaseName = "C:Documents and SettingsPcToshibaSatelliteEscritorioRegHorasRegDocente.mdb"
    Data_Doc.RecordSource = "Docente"


    With Combo1
    .Clear
    Data_Carr.Refresh
    While Not Data_Carr.Recordset.EOF
    .AddItem Data_Carr.Recordset!IdCarrera
    Data_Carr.Recordset.MoveNext
    Wend
    End With

    With Combo2
    .Clear
    Data_Asig.Refresh
    While Not Data_Asig.Recordset.EOF
    .AddItem Data_Asig.Recordset!IdAsig
    Data_Asig.Recordset.MoveNext
    Wend
    End With

    txtRut = ""
    txtNombre = ""
    txtcarrera = ""
    txtAsignatura = ""
    txtHoraSema = ""
    txtHoraSeme = ""
    txtHoraReal = ""
    txtDifHoras = ""
    txtJornada = ""

    txtFechIni.Enabled = True
    txtFechTerm.Enabled = False
    txtRut.Enabled = False
    txtNombre.Enabled = False
    txtCarre.Enabled = False
    txtAsig.Enabled = False
    Combo1.Enabled = False
    Combo2.Enabled = False
    txtHoraSema.Enabled = False
    txtHoraSeme.Enabled = False
    txtDifHoras.Enabled = False
    txtJornada.Enabled = False

    End Sub

    Private Sub mnuAsignatura_Click()
    frmDocente.Hide
    frmAsignatura.Show
    End Sub

    Private Sub mnuCarrera_Click()
    frmCarrera.Show
    frmDocente.Hide
    End Sub

    Private Sub mnuDocente_Click()
    frmDocente.Show
    End Sub

    Private Sub txtAsignatura_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If txtAsignatura = "" Then
    r = MsgBox("Ingrese un nombre", vbOKOnly, "Error")
    txtAsignatura.SetFocus
    Else
    txtAsignatura.Enabled = False
    txtHoraSema.Enabled = True
    txtHoraSema.SetFocus
    End If
    End If
    End Sub

    Private Sub txtCarrera_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If txtcarrera = "" Then
    r = MsgBox("Ingrese un nombre", vbOKOnly, "Error")
    txtcarrera.SetFocus
    Else
    txtcarrera.Enabled = False
    txtAsignatura.Enabled = True
    txtAsignatura.SetFocus
    End If
    End If
    End Sub

    Private Sub txtAsig_Change()
    txtAsig.Text = Combo2.Text
    End Sub

    Private Sub txtCarre_Change()
    txtCarre.Text = Combo1.Text
    End Sub

    Private Sub txtDifHoras_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If IsNumeric(txtDifHoras) Then
    txtDifHoras.Enabled = False
    txtJornada.Enabled = True
    txtJornada.SetFocus
    Else
    r = MsgBox("fecha no válida", vbCritical, "ERROR!!!")
    txtDifHoras.Text = ""
    txtDifHoras.SetFocus
    End If
    End If
    End Sub

    Private Sub txtFechIni_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If IsDate(txtFechIni) Then
    txtFechIni.Enabled = False
    txtFechTerm.Enabled = True
    txtFechTerm.SetFocus
    Else
    r = MsgBox("fecha no válida", vbCritical, "ERROR!!!")
    txtFechIni.Text = ""
    txtFechIni.SetFocus
    End If
    End If
    End Sub

    Private Sub txtFechTerm_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If IsDate(txtFechTerm) Then
    txtFechTerm.Enabled = False
    txtRut.Enabled = True
    txtRut.SetFocus
    Else
    r = MsgBox("Fecha no válida", vbCritical, "ERROR!!!")
    txtFechTerm.Text = ""
    txtFechTerm.SetFocus
    End If
    End If
    End Sub

    Private Sub txtHoraReal_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If IsNumeric(txtHoraReal) Then
    txtHoraReal.Enabled = False
    txtDifHoras.Enabled = True
    txtDifHoras.SetFocus
    Else
    r = MsgBox("INGRESE CIFRAS NUMERICAS", vbCritical, "ERROR!!!")
    txtHoraReal.Text = ""
    txtHoraReal.SetFocus
    End If
    End If
    End Sub

    Private Sub txtHoraSema_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If IsNumeric(txtHoraSema) Then
    txtHoraSema.Enabled = False
    txtHoraSeme.Enabled = True
    txtHoraSeme.SetFocus
    Else
    r = MsgBox("INGRESE SOLO CIFRAS NUMERICAS", vbCritical, "ERROR!!!")
    txtHoraSema.Text = ""
    txtHoraSema.SetFocus
    End If
    End If
    End Sub
    Private Sub txtHoraSeme_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If IsNumeric(txtHoraSeme) Then
    txtHoraSeme.Enabled = False
    txtHoraReal.Enabled = True
    txtHoraReal.SetFocus
    Else
    r = MsgBox("INGRESE CIFRAS NUMERICAS", vbCritical, "ERROR!!!")
    txtHoraSeme.Text = ""
    txtHoraSeme.SetFocus
    End If
    End If
    End Sub

    Private Sub txtJornada_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    txtJornada.Enabled = False
    cmdGuardar.Enabled = True
    cmdGuardar.SetFocus
    End If

    End Sub

    Private Sub Txtnombre_keypress(KeyAscii As Integer)
    If KeyAscii = 13 Then
    If txtNombre = "" Then
    r = MsgBox("Ingrese un nombre", vbOKOnly, "Error")
    txtNombre.SetFocus
    Else
    txtNombre.Enabled = False
    Combo1.Enabled = True
    Combo1.SetFocus
    End If
    End If

    End Sub

    Private Sub txtRut_KeyPress(KeyAscii As Integer)
    If KeyAscii = 13 And Len(txtRut) > 0 Then
    vrut (Text)
    Data_Doc.Recordset.Index = "ordrut"
    Data_Doc.Recordset.Seek "=", txtRut
    If Data_Doc.Recordset.NoMatch Then
    MsgBox "NUEVO REGISTRO"
    txtRut.Enabled = False
    txtNombre.Enabled = True
    txtNombre.SetFocus
    Else
    MsgBox "CODIGO REGISTRADO"
    txtRut.Enabled = False
    txtRut = Data_Doc.Recordset("Rut")
    txtNombre = Data_Doc.Recordset("Nombre")
    txtNomCarrera = Data_Doc.Recordset("NomCarrera")
    txtNomAsig = Data_Doc.Recordset("NomAsig")
    txtHoraSema = Data_Doc.Recordset("HoraSema")
    txtHoraSeme = Data_Doc.Recordset("HoraSeme")
    txtHoraReal = Data_Doc.Recordset("HoraRealsem")
    txtDifHoras = Data_Doc.Recordset("DifHora")
    txtJornada = Data_Doc.Recordset("Jornada")
    End If
    End If
    End Sub



  13. deberias guardadlo directamente desde el combo... no tiene caso enviarlo a un text... intentalo asi,,, o expon mejor tu problema.. no entiendo para que pones todo el codigo
    saludos



  14. esta bueno tu explicacion pero muy largo lo has hecho men pero igual se entiende graxias por tu aporte. mas bien un favor no conoces una pagina donde me pueda bajar libros de visual basic y si es gratis mejor jaja lo necesito urgente haber si me lo mandan ah mi correro se agradece

agregar comentario


Se permiten las etiquetas HTML , y

. Si ingresa alguna direcci?n web o direcci?n de email ser?n convertidos en enlaces autom?ticamente.





publicidad

API DE FACEBOOK
GOOGLE CALENDAR API
GOOGLE MAPS API