100% encontró este documento útil (1 voto)
370 vistas9 páginas

Configuración de ListView en VB.NET

El control ListView de Windows Forms muestra una lista de elementos con iconos y texto. Puede configurarse para mostrar los elementos de diferentes formas, como iconos grandes o pequeños, o en varias columnas. La propiedad Items contiene los elementos mostrados, y SelectedItems los elementos seleccionados. El formulario muestra los datos de clientes en un ComboBox y las órdenes correspondientes al cliente seleccionado en un ListView.
Derechos de autor
© Attribution Non-Commercial (BY-NC)
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX o lee en línea desde Scribd
100% encontró este documento útil (1 voto)
370 vistas9 páginas

Configuración de ListView en VB.NET

El control ListView de Windows Forms muestra una lista de elementos con iconos y texto. Puede configurarse para mostrar los elementos de diferentes formas, como iconos grandes o pequeños, o en varias columnas. La propiedad Items contiene los elementos mostrados, y SelectedItems los elementos seleccionados. El formulario muestra los datos de clientes en un ComboBox y las órdenes correspondientes al cliente seleccionado en un ListView.
Derechos de autor
© Attribution Non-Commercial (BY-NC)
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX o lee en línea desde Scribd

Listview

El control ListView de formularios Windows Forms muestra una lista de


elementos con iconos. Puede utilizar una vista de lista para crear una
interfaz de usuario similar al panel derecho del Explorador de Windows.
El control tiene cuatro modos de vista: LargeIcon, SmallIcon, List y
Details. El modo LargeIcon muestra iconos grandes junto al texto de los
elementos; si el control es lo suficientemente grande, los elementos
aparecen en varias columnas. El modo SmallIcon es igual, pero muestra
iconos pequeños. El modo List muestra iconos pequeños, pero siempre
en una sola columna. El modo Details muestra los elementos en varias
columnas.

La propiedad clave del control ListView es Items, que contiene los


elementos que muestra el control. La propiedad

SelectedItems contiene la colección de elementos seleccionados


actualmente en el control. Si la propiedad MultiSelect se establece en
true, el usuario puede seleccionar varios elementos, por ejemplo,
para arrastrar y colocar en otro control varios elementos a la vez. Si
la propiedad CheckBoxes se establece en true, el control ListView puede
mostrar casillas de verificación junto a los [Link] propiedad
Activation determina el tipo de acción que debe realizar el usuario para
activar los elementos de la lista: las opciones son Standard, OneClick
y TwoClick. La activación OneClick necesita un solo clic para
activar el elemento. La activación TwoClick requiere que el usuario
haga doble clic para activar el elemento; un solo clic cambia el color del
texto del elemento. La activación Standard requiere que el usuario
haga doble clic para activar un elemento, pero la apariencia del
elemento no cambia.

Empleando la BDD BDventas(Clientes, Fac_cabe, Fac_deta,artículos)


realizar el formulario:
Listbox1

LISTVIEW1
Configurando el ListView

Codificacion del Formulario


Imports [Link]
Imports [Link]
Public Class Form1
Dim cn As New SqlConnection("Server=localhost;Integrated
Security=SSPI;database=ventas")
Private Sub Form1_Load(ByVal sender As [Link], ByVal e As
[Link]) Handles [Link]
'Mostrar los empleados
Dim da As New SqlDataAdapter("Select cod_emp,nombre from empleado", cn)
Dim tbl As New DataTable
[Link](tbl) [Link] = tbl
[Link] = "nombre"
[Link] = "cod_emp"
Call formatoListview1()
End Sub

Sub formatoListview1()
'dando formato al listview
With ListView1
.[Link]()
.View = [Link]
.[Link]("Factura", 80, [Link])
.[Link]("Sub Total", 80, [Link])
.[Link]("Igv", 80, [Link])
.[Link]("Total", 80, [Link])
.GridLines = True
.FullRowSelect = True
End With
End Sub

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal


e As
[Link]) Handles [Link]
'Mostrar las 5 ordenes con mayor igv
Try 'controlador de errores
Dim codigo As String = [Link]
Dim cadsql As String = "Select top 5 Num_fact,sub_total,igv,total " & _
" from facturas Where cod_emp=@codigo"
Dim cmd As New SqlCommand(cadsql, cn)
[Link] = [Link] [Link]()
[Link]("@codigo", [Link], 5).Value = codigo
Dim dr As SqlDataReader = [Link]
If [Link] = True Then
[Link]()
Dim LstItem As ListViewItem

While [Link]
LstItem = [Link](dr(0).ToString)
[Link](dr(1).ToString)
[Link](dr(2).ToString)
[Link](dr(3).ToString)
End While
End If
[Link] = [Link]
Catch ex As Exception
Finally [Link]()
End Try
End Sub

Private Sub ListView1_Click(ByVal sender As [Link], ByVal e As


[Link]) Handles [Link]
'Mostrando los datos de la columna
With ListView1
Dim factura As String = .[Link](.SelectedIndices(0)).Text
Dim subtotal As String = .[Link](.SelectedIndices(0)).SubItems(1).Text
[Link](factura & " - " & subtotal)
End With
End Sub
End Class

Las Tablas de la base de datos Ventas


CREATE TABLE Empleado(
cod_emp char(5) Not NULL ,
nombre varchar(25) Not NULL ,
cargo varchar(20) NULL ,

CREATE TABLE Facturas (


num_fact char(6) Not Null,
cod_emp char(5),
cod_cli char(5),
sub_total decimal(8,2),
igv decimal(8,2),
total decimal(8,2),
fecha datetime,
)
Llenar datos consistentes

AddHandler (Instrucción)

Asocia un evento a un controlador de eventos en tiempo de ejecución.

AddHandler event, AddressOf eventhandler

Partes

event Nombre del evento que se va a controlar.


Eventhandler Nombre del procedimiento que controlará el evento.

Comentarios

Las instrucciones AddHandler y RemoveHandler permiten iniciar y detener el


controlador del evento en cualquier momento de la ejecución del programa.

La firma del procedimiento eventhandler debe coincidir con la firma del evento event.

La palabra clave Handles y la instrucción AddHandler permiten especificar que


ciertos procedimientos controlen eventos determinados, pero hay diferencias entre
ambos. La instrucción AddHandler conecta los procedimientos a los eventos en
tiempo de ejecución. Utilice la palabra clave Handles al definir un
procedimiento para especificar que controla un evento determinado. Para obtener
más información, vea Handles.

En los eventos personalizados, la instrucción AddHandler invoca al descriptor de


acceso AddHandler del evento. Para obtener más información sobre eventos
personalizados, vea Event (Instrucción).

Ejemplo

Sub TestEvents()

Dim Obj As New Class1

' Associate an event handler with an event. AddHandler Obj.Ev_Event, AddressOf


EventHandler

' Call the method to raise the event. [Link]()

' Stop handling events.

RemoveHandler Obj.Ev_Event, AddressOf EventHandler

' This event will not be handled. [Link]()

End Sub

Sub EventHandler()

' Handle the event. MsgBox("EventHandler caught event.")

End Sub

Public Class Class1

' Declare an event. Public Event Ev_Event() Sub CauseSomeEvent()


' Raise an event. RaiseEvent Ev_Event()

End Sub

End Class

RemoveHandler (Instrucción)

Quita la asociación entre un evento y un controlador de eventos.

RemoveHandler event, AddressOf eventhandler

Partes

event

Nombre del evento que se va a controlar.

eventhandler

Nombre del procedimiento que controla actualmente el evento.

Comentarios

Las instrucciones AddHandler y RemoveHandler permiten iniciar y detener el


control del evento de un evento específico en cualquier momento de la ejecución
del programa.

Para los eventos personalizados, la instrucción RemoveHandler llama al


descriptor de acceso RemoveHandler del evento. Para obtener más información
sobre eventos personalizados, vea Event (Instrucción).

Ejemplo

Sub TestEvents()

Dim Obj As New Class1

' Associate an event handler with an event. AddHandler Obj.Ev_Event, AddressOf


EventHandler

' Call the method to raise the event. [Link]()

' Stop handling events.

RemoveHandler Obj.Ev_Event, AddressOf EventHandler

' This event will not be handled. [Link]()

End Sub

Sub EventHandler()
' Handle the event. MsgBox("EventHandler caught event.")

End Sub

Public Class Class1

' Declare an event. Public Event Ev_Event() Sub CauseSomeEvent()

' Raise an event. RaiseEvent Ev_Event()

End Sub

End Class

Veamos un ejemplo con el llenado de datos en un ComboBox, mediante el


evento form1_load, y llamando a la vez al evento SelectedIndexChanged del
ComboBox.

Al momento de llenar el ComboBox1 en el evento Form1_Load,


usted evitara llamar al evento SelectedIndexChanged con la finalidad
de mostrar datos erróneos, debido a que se esta asignando objetos y
campos en sus propiedades.

Imports [Link]

Imports [Link]

Public Class Form1

Dim cn As New SqlConnection("Server=localhost;Integrated


Security=SSPI;database=NorthWind")

Private Sub Form1_Load(ByVal sender As [Link], ByVal e As


[Link]) Handles

[Link]

MostrarOrdenes()

End Sub

Sub MostrarOrdenes()

RemoveHandler [Link], _ AddressOf


ComboBox1_SelectedIndexChanged

Dim da As New SqlDataAdapter("Select CustomerID,CompanyName From


Customers", cn) Dim tbl As New DataTable
[Link](tbl)

[Link] = tbl [Link] = "CompanyName"


[Link] = "CustomerID"

AddHandler [Link], _

AddressOf ComboBox1_SelectedIndexChanged

End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As [Link],


ByVal e As

[Link]) Handles [Link]

Dim da As New SqlDataAdapter("Select OrderID From Orders Where


CustomerID='" & [Link]

& "'", cn)

Dim tbl As New DataTable [Link](tbl) [Link] = tbl

[Link] = "OrderID"

End Sub

End Class

Common questions

Con tecnología de IA

The 'RemoveHandler' instruction is used to detach a method from an event-handler list in .NET, reversing the effect of 'AddHandler'. This method stops the procedure from handling the associated event, which is useful for controlling resource use in applications, or to change the event's associated logic at runtime. It is particularly important in environments where dynamic event subscription and unsubscription are required, reducing memory footprint and avoiding logic errors by ensuring events are not inadvertently handled after they've served their purpose .

The document describes using database tables in ListView and ComboBox controls by populating these controls with data retrieved via SQL queries. For the ListView control, data like 'num_fact' and 'sub_total' are fetched from the 'Facturas' table and displayed in the Details view. The ComboBox control is populated with 'CustomerID' and 'CompanyName' from the 'Customers' table in a similar manner. Using SQLDataAdapter and DataTable objects, data is retrieved, assigned to controls, and managed by event handlers such as the SelectedIndexChanged for dynamic data operations .

Using 'AddHandler' differs from the 'Handles' keyword by allowing dynamic association of event handlers during runtime, offering flexibility not possible with 'Handles', which binds event handlers at compile-time. 'AddHandler' is used for custom dynamic event connections and is preferred in scenarios requiring runtime logic modification, such as in plugin architectures or where event handlers may be conditionally bound/unbound. 'Handles', requiring static binding, typically suits static or predefined event-action pairs .

The 'AddHandler' instruction dynamically associates a method with an event at runtime. It requires specifying both the event to be handled and the procedure (eventhandler) that will manage the event. This allows for flexible event handling, enabling developers to start or stop responding to events without pre-compiling this logic into the code. The eventhandler's signature must match the event's signature. This approach is beneficial for custom events, providing the ability to invoke accessors specific to custom event handling scenarios .

The ListView control in Windows Forms is used to display a list of items with optional icons. It supports four view modes: LargeIcon, SmallIcon, List, and Details. The LargeIcon and SmallIcon modes display items with large or small icons respectively, arranged in multiple columns if space permits. The List mode shows small icons in a single column. The Details mode presents items in multiple columns, similar to a grid. Significant properties include Items, which holds the current items in the view, SelectedItems for selected elements, and MultiSelect for enabling multiple item selection. When CheckBoxes is true, checkboxes appear next to items. The Activation property determines the interaction model: Standard, OneClick, or TwoClick, which affect how items are activated upon user interaction .

The 'View' property in the ListView control determines how items and sub-items are displayed, offering modes such as LargeIcon, SmallIcon, List, and Details. By leveraging this property, developers can enhance user experience by selecting the most appropriate layout for the data type and user interaction. For instance, Details view is ideal for comparing detailed information across columns, while LargeIcon may be preferred for visually distinctive items. Adjusting the View property allows applications to cater to different user needs and contextual data presentation goals .

The 'SelectedIndexChanged' event in a ComboBox control serves to execute actions whenever the ComboBox's selected item changes. This event enables dynamic updates or dependent operations in response to user selections. For instance, data filtered by the newly selected value can be loaded into another control, like a ListBox. In the document, disabling this event during initial data binding prevents it from prematurely firing and potentially causing errors or unintended operations, illustrating its importance in maintaining control flow consistency .

In ListView, multi-select operations are enabled via the MultiSelect property. This allows users to select multiple items simultaneously, facilitating batch operations like drag-and-drop or collective actions like deleting multiple entries. These operations enhance user efficiency, particularly in data management contexts where handling multiple items at once is common. However, they also add complexity to the application logic, requiring careful handling of multiple selections to ensure data integrity during actions like deletions or modifications .

The ListView control's activation types—Standard, OneClick, and TwoClick—impact how users interact with applications by dictating the number of clicks needed to activate an item. Standard activation requires double-clicking, suitable for interfaces where accidental activation should be minimized. OneClick activation facilitates quicker access through single clicks but may lead to accidental activations in dense interfaces. TwoClick provides a middle ground by highlighting the item first, requiring a follow-up click to activate, useful for applications needing a confirmation step. These choices influence application responsiveness and user error rates .

'Try...Catch' blocks are crucial for managing exceptions during data transactions in a ListView control. They help in gracefully handling runtime errors like connection failures or invalid queries, ensuring that the application remains stable. By catching exceptions, developers can provide user feedback through messages or logs, improving troubleshooting and preventing the entire application from crashing. It encapsulates code that accesses the database, mitigating risks associated with database connectivity, and allows for recovery actions to be implemented .

También podría gustarte