Programación con formularios Windows Forms
Tutorial: Implementar el modo virtual en el control DataGridView de formularios Windows Forms Vea también Contraer todo Expandir todo Filtro de lenguaje: To Todos dos Filtro de lenguaje: !ltiple Filtro de lenguaje: Visual "asic Filtro Fi ltro de lenguaje: C# Filtro de lenguaje: C$$ Filtro de lenguaje: %# Filtro de lenguaje: %&cript Visual "asic '(eclaración) Visual "asic '*so) C# C$$ %# %&cript &i desea mostrar grandes +ol!menes de datos en formato de tabla en un control (ata,ridView- puede establecer la propiedad Virtualode en true . true . administrar de forma expl/cita la interacción del control con el almacén de datos0 Esto le permite ajustar el rendimiento del control en esta situación0 El control DataGridView proporciona DataGridView proporciona +arios e+entos 1ue puede controlar para interactuar con un almacén de datos personali2ado0 Este tutorial le gu/a a tra+és del proceso de implementar estos controladores de e+entos0 En el ejemplo de código de este tema se utili2a un o rigen de datos mu. sencillo para fines de ilustración0 En una configuración de producción- normalmente cargar3 sólo las filas 1ue necesite mostrar en cac4é . controlar3 e+entos DataGridView para DataGridView para interactuar con la cac4é . actuali2arla0 Para obtener m3s información- +ea 5mplementar el modo +irtual mediante la carga de datos %ust65n6Time %ust65n6Time en el control (ata,ridView de formularios Windows Forms Para copiar el código de este tema como un listado sencillo- +ea Cómo: 5mplementar el modo +irtual en el control (ata,ridView de formularios Windows Forms0 Forms0
Crear el formulario Para implementar el modo virtual 70
Cree Cree una clase clase 1ue 1ue deri+ deri+a a de Form Form . contie contiene ne un un contro controll DataGridView0 DataGridView0 El código siguiente contiene alguna iniciali2ación b3sica0 &e declaran algunas +ariables 1ue se utili2ar3n en pasos posteriores- se proporciona un método Main . un dise8o de formulario sencillo del constructor de clase0
Visual Basic
Copiar código
Imports System Imports System.Windows.Forms Public Class Form1 Inherits Form Private WithEvents dataGridiew1 !s "ew #ataGridiew
%$ & #eclare an !rray'ist to serve as the data store. Private customers !s "ew System.Collections.!rray'ist$% & #eclare a Customer ob(ect to store data )or a row bein* edited. Private customerInEdit !s Customer & #eclare a variable to store the inde+ o) a row bein* edited. & ! value o) ,1 indicates that there is no row currently in edit. Private rowInEdit !s Inte*er - ,1 & #eclare a variable to indicate the commit scope. & Set this value to )alse to use cell,level commit scope. Private rowScopeCommit !s oolean - /rue 0S/!/hread!ttribute$% 2 Public Shared Sub Main$% !pplication.3un$"ew Form1$%% End Sub Public Sub "ew$% & Initiali4e the )orm. Me.dataGridiew1.#oc5 - #oc5Style.Fill Me.Controls.!dd$Me.dataGridiew1% Me./e+t - 6#ataGridiew virtual,mode demo $row,level commit scope%6 End Sub
...
End Class
C#
Copiar código
usin* System7 usin* System.Windows.Forms7 public class Form1 8 Form 9 private #ataGridiew dataGridiew1 - new #ataGridiew$%7 :: #eclare an !rray'ist to serve as the data store. private System.Collections.!rray'ist customers new System.Collections.!rray'ist$%7 :: #eclare a Customer ob(ect to store data )or a row bein* edited. private Customer customerInEdit7 :: #eclare a variable to store the inde+ o) a row bein* edited. :: ! value o) ,1 indicates that there is no row currently in edit. private int rowInEdit - ,17 :: #eclare a variable to indicate the commit scope. :: Set this value to )alse to use cell,level commit scope. private bool rowScopeCommit - true7
;S/!/hread!ttribute$%< public static void Main$% 9 !pplication.3un$new Form1$%%7 = public Form1$% 9 :: Initiali4e the )orm. this.dataGridiew1.#oc5 - #oc5Style.Fill7
this.Controls.!dd$this.dataGridiew1%7 this.'oad >- new Event?andler$Form12'oad%7 this./e+t - 6#ataGridiew virtual,mode demo $row,level commit scope%67 =
... = 90
5mplemente un controlador para el e+ento oad del formulario 1ue iniciali2a el control DataGridView . rellena el almacén de datos con +alores de ejemplo0
Visual Basic
Copiar código
Private Sub Form12'oad$yal sender !s @b(ectA yal e !s Event!r*s% 2 ?andles Me.'oad & Enable virtual mode. Me.dataGridiew1.irtualMode - /rue & !dd columns to the #ataGridiew. #im company"ameColumn !s "ew #ataGridiew/e+to+Column$% With company"ameColumn .?eader/e+t - 6Company "ame6 ."ame - 6Company "ame6 End With #im contact"ameColumn !s "ew #ataGridiew/e+to+Column$% With contact"ameColumn .?eader/e+t - 6Contact "ame6 ."ame - 6Contact "ame6 End With Me.dataGridiew1.Columns.!dd$company"ameColumn% Me.dataGridiew1.Columns.!dd$contact"ameColumn% Me.dataGridiew1.!utoSi4eColumnsMode - 2 #ataGridiew!utoSi4eColumnsMode.!llCells & !dd some sample entries to the data store. Me.customers.!dd$"ew Customer$6on app&6A
6'aurence 'ebihan6%% Me.customers.!dd$"ew Customer$6ottom,#ollar Mar5ets6A 2 6Eli4abeth 'incoln6%% Me.customers.!dd$"ew Customer$6&s evera*es6A 6ictoria !shworth6%% & Set the row countA includin* the row )or new records. Me.dataGridiew1.3owCount - B End Sub
C#
Copiar código
private void Form12'oad$ob(ect senderA Event!r*s e% 9 :: Enable virtual mode. this.dataGridiew1.irtualMode - true7 :: Connect the virtual,mode events to event handlers. this.dataGridiew1.Cellalue"eeded >- new #ataGridiewCellalueEvent?andler$dataGridiew12Cellalue"ee this.dataGridiew1.CellaluePushed >- new #ataGridiewCellalueEvent?andler$dataGridiew12CellaluePus this.dataGridiew1."ew3ow"eeded >- new #ataGridiew3owEvent?andler$dataGridiew12"ew3ow"eed this.dataGridiew1.3owalidated >- new #ataGridiewCellEvent?andler$dataGridiew123owalida this.dataGridiew1.3ow#irtyState"eeded >- new uestionEvent?andler$dataGridiew123ow#irtyState"eed this.dataGridiew1.Cancel3owEdit >- new uestionEvent?andler$dataGridiew12Cancel3owEdit%7 this.dataGridiew1.Dser#eletin*3ow >- new #ataGridiew3owCancelEvent?andler$dataGridiew12Dser#eletin* :: !dd columns to the #ataGridiew. #ataGridiew/e+to+Column company"ameColumn - new
#ataGridiew/e+to+Column$%7 company"ameColumn.?eader/e+t - 6Company "ame67 company"ameColumn."ame - 6Company "ame67 #ataGridiew/e+to+Column contact"ameColumn - new #ataGridiew/e+to+Column$%7 contact"ameColumn.?eader/e+t - 6Contact "ame67 contact"ameColumn."ame - 6Contact "ame67 this.dataGridiew1.Columns.!dd$company"ameColumn%7 this.dataGridiew1.Columns.!dd$contact"ameColumn%7 this.dataGridiew1.!utoSi4eColumnsMode #ataGridiew!utoSi4eColumnsMode.!llCells7 :: !dd some sample entries to the data store. this.customers.!dd$new Customer$ 6on app&6A 6'aurence 'ebihan6%%7 this.customers.!dd$new Customer$ 6ottom,#ollar Mar5ets6A 6Eli4abeth 'incoln6%%7 this.customers.!dd$new Customer$ 6&s evera*es6A 6ictoria !shworth6%%7 :: Set the row countA includin* the row )or new records. this.dataGridiew1.3owCount - B7
= ;0
5mplemente un controlador para el e+ento CellValue
Visual Basic
Copiar código
Private Sub dataGridiew12Cellalue"eeded$yal sender !s @b(ectA 2 yal e !s System.Windows.Forms.#ataGridiewCellalueEvent!r*s% 2 ?andles dataGridiew1.Cellalue"eeded & I) this is the row )or new recordsA no values are needed. I) e.3owInde+ - Me.dataGridiew1.3owCount , 1 /hen 3eturn End I)
#im customer/mp !s Customer - "othin* & Store a re)erence to the Customer ob(ect )or the row bein* painted. I) e.3owInde+ - rowInEdit /hen customer/mp - Me.customerInEdit Else customer/mp C/ype$Me.customers$e.3owInde+%A Customer% End I) & Set the cell value to paint usin* the Customer ob(ect retrieved. Select Case Me.dataGridiew1.Columns$e.ColumnInde+%."ame Case 6Company "ame6 e.alue - customer/mp.Company"ame Case 6Contact "ame6 e.alue - customer/mp.Contact"ame End Select End Sub
C#
Copiar código
private void dataGridiew12Cellalue"eeded$ob(ect senderA System.Windows.Forms.#ataGridiewCellalueEvent!r*s e% 9 :: I) this is the row )or new recordsA no values are needed. i) $e.3owInde+ -- this.dataGridiew1.3owCount , 1% return7 Customer customer/mp - null7 :: Store a re)erence to the Customer ob(ect )or
the row bein* painted. i) $e.3owInde+ -- rowInEdit% 9 customer/mp - this.customerInEdit7 = else 9 customer/mp $Customer%this.customers;e.3owInde+<7 = :: Set the cell value to paint usin* the Customer ob(ect retrieved. switch $this.dataGridiew1.Columns;e.ColumnInde+<."ame% 9 case 6Company "ame68 e.alue - customer/mp.Company"ame7 brea57 case 6Contact "ame68 e.alue - customer/mp.Contact"ame7 brea57
= = =0
5mplemente un controlador para el e+ento CellValuePus4ed 1ue almacena un +alor de celda editado en el objeto Customer 1ue representa la fila editada0 Este e+ento se produce cada +e2 1ue el usuario confirma un cambio de +alor de celda0
Visual Basic
Copiar código
Private Sub dataGridiew12CellaluePushed$yal sender !s @b(ectA 2 yal e !s System.Windows.Forms.#ataGridiewCellalueEvent!r*s% 2 ?andles dataGridiew1.CellaluePushed #im customer/mp !s Customer - "othin* & Store a re)erence to the Customer ob(ect )or the row bein* edited.
I) e.3owInde+ 0 Me.customers.Count /hen & I) the user is editin* a new rowA create a new Customer ob(ect. I) Me.customerInEdit Is "othin* /hen Me.customerInEdit - "ew Customer$ 2 C/ype$Me.customers$e.3owInde+%A Customer%.Company"ameA 2 C/ype$Me.customers$e.3owInde+%A Customer%.Contact"ame% End I) customer/mp - Me.customerInEdit Me.rowInEdit - e.3owInde+
Else customer/mp - Me.customerInEdit End I)
& Set the appropriate Customer property to the cell value entered. #im newalue !s Strin* - /ryCast$e.alueA Strin*% Select Case Me.dataGridiew1.Columns$e.ColumnInde+%."ame Case 6Company "ame6 customer/mp.Company"ame - newalue Case 6Contact "ame6 customer/mp.Contact"ame - newalue End Select End Sub
C#
Copiar código
private void dataGridiew12CellaluePushed$ob(ect senderA System.Windows.Forms.#ataGridiewCellalueEvent!r*s e% 9 Customer customer/mp - null7
:: Store a re)erence to the Customer ob(ect )or the row bein* edited. i) $e.3owInde+ 0 this.customers.Count% 9 :: I) the user is editin* a new rowA create a new Customer ob(ect. i) $this.customerInEdit -- null% 9 this.customerInEdit - new Customer$ $$Customer%this.customers;e.3owInde+<%.Company"ameA $$Customer%this.customers;e.3owInde+<%.Contact"ame%7 = customer/mp - this.customerInEdit7 this.rowInEdit - e.3owInde+7 = else 9 customer/mp - this.customerInEdit7 = :: Set the appropriate Customer property to the cell value entered. Strin* newalue - e.alue as Strin*7 switch $this.dataGridiew1.Columns;e.ColumnInde+<."ame% 9 case 6Company "ame68 customer/mp.Company"ame - newalue7 brea57 case 6Contact "ame68 customer/mp.Contact"ame - newalue7 brea57
= = >0
5mplemente un controlador para el e+ento
Copiar código
Visual Basic
Private Sub dataGridiew12"ew3ow"eeded$yal sender !s @b(ectA 2 yal e !s System.Windows.Forms.#ataGridiew3owEvent!r*s% 2 ?andles dataGridiew1."ew3ow"eeded & Create a new Customer ob(ect when the user edits & the row )or new records. Me.customerInEdit - "ew Customer$% Me.rowInEdit - Me.dataGridiew1.3ows.Count , 1 End Sub
C#
Copiar código
private void dataGridiew12"ew3ow"eeded$ob(ect senderA System.Windows.Forms.#ataGridiew3owEvent!r*s e% 9 :: Create a new Customer ob(ect when the user edits :: the row )or new records. this.customerInEdit - new Customer$%7 this.rowInEdit - this.dataGridiew1.3ows.Count , 17 = @0
5mplemente un controlador para el e+ento ?owValidated 1ue guarda las filas nue+as o modificadas en el almacén de datos0 Este e+ento aparece cada +e2 1ue el usuario cambia la fila actual0
Visual Basic
Copiar código
Private Sub dataGridiew123owalidated$yal sender !s @b(ectA 2 yal e !s System.Windows.Forms.#ataGridiewCellEvent!r*s% 2 ?andles dataGridiew1.3owalidated & Save row chan*es i) any were made and release the edited
& Customer ob(ect i) there is one. I) e.3owInde+ - Me.customers.Count !nd!lso 2 e.3owInde+ 0 Me.dataGridiew1.3ows.Count , 1 /hen & !dd the new Customer ob(ect to the data store.
Me.customers.!dd$Me.customerInEdit% Me.customerInEdit - "othin* Me.rowInEdit - ,1
ElseI) "ot $Me.customerInEdit Is "othin*% !nd!lso 2 e.3owInde+ 0 Me.customers.Count /hen & Save the modi)ied Customer ob(ect in the data store. Me.customers$e.3owInde+% Me.customerInEdit Me.customerInEdit - "othin* Me.rowInEdit - ,1 ElseI) Me.dataGridiew1.ContainsFocus /hen Me.customerInEdit - "othin* Me.rowInEdit - ,1 End I) End Sub
C#
Copiar código
private void dataGridiew123owalidated$ob(ect senderA System.Windows.Forms.#ataGridiewCellEvent!r*s e% 9 :: Save row chan*es i) any were made and release the edited :: Customer ob(ect i) there is one.
i) $e.3owInde+ - this.customers.Count e.3owInde+ - this.dataGridiew1.3ows.Count , 1% 9 :: !dd the new Customer ob(ect to the data store. this.customers.!dd$this.customerInEdit%7 this.customerInEdit - null7 this.rowInEdit - ,17 = else i) $this.customerInEdit - null e.3owInde+ 0 this.customers.Count% 9 :: Save the modi)ied Customer ob(ect in the data store. this.customers;e.3owInde+< this.customerInEdit7 this.customerInEdit - null7 this.rowInEdit - ,17 = else i) $this.dataGridiew1.ContainsFocus% 9 this.customerInEdit - null7 this.rowInEdit - ,17 = = A0
5mplemente un controlador para el e+ento ?ow(irt.&tate
Visual Basic
Copiar código
Private Sub dataGridiew123ow#irtyState"eeded$yal sender !s @b(ectA 2 yal e !s System.Windows.Forms.uestionEvent!r*s% 2 ?andles dataGridiew1.3ow#irtyState"eeded I) "ot rowScopeCommit /hen
& In cell,level commit scopeA indicate whether the value & o) the current cell has been modi)ied. e.3esponse Me.dataGridiew1.IsCurrentCell#irty End I) End Sub
C#
Copiar código
private void dataGridiew123ow#irtyState"eeded$ob(ect senderA System.Windows.Forms.uestionEvent!r*s e% 9 i) $rowScopeCommit% 9 :: In cell,level commit scopeA indicate whether the value :: o) the current cell has been modi)ied. e.3esponse this.dataGridiew1.IsCurrentCell#irty7 = = 7D0 5mplemente un controlador para el e+ento CancelRowdit 1ue descarta los +alores del objeto Customer 1ue representa la fila actual0 &e produce este e+ento cuando el usuario se8ala la re+ersión de la fila presionando dos +eces E&C en modo de edición o una +e2 fuera del modo de edición0
Visual Basic
Copiar código
Private Sub dataGridiew12Cancel3owEdit$yal sender !s @b(ectA 2 yal e !s System.Windows.Forms.uestionEvent!r*s% 2 ?andles dataGridiew1.Cancel3owEdit I) Me.rowInEdit - Me.dataGridiew1.3ows.Count , !nd!lso 2 Me.rowInEdit - Me.customers.Count /hen
& I) the user has canceled the edit o) a newly created rowA & replace the correspondin* Customer ob(ect with a newA empty one. Me.customerInEdit - "ew Customer$%
Else
& I) the user has canceled the edit o) an e+istin* rowA & release the correspondin* Customer ob(ect. Me.customerInEdit - "othin* Me.rowInEdit - ,1 End I) End Sub
C#
Copiar código
private void dataGridiew12Cancel3owEdit$ob(ect senderA System.Windows.Forms.uestionEvent!r*s e% 9 i) $this.rowInEdit -this.dataGridiew1.3ows.Count , this.rowInEdit -- this.customers.Count% 9 :: I) the user has canceled the edit o) a newly created rowA :: replace the correspondin* Customer ob(ect with a newA empty one. this.customerInEdit - new Customer$%7 = else 9 :: I) the user has canceled the edit o) an e+istin* rowA :: release the correspondin* Customer
ob(ect. this.customerInEdit - null7 this.rowInEdit - ,17 = = 770 5mplemente un controlador para el e+ento *ser(eleting?ow 1ue suprime un objeto Customer existente del almacén de datos o descarta un objeto Customer no guardado 1ue representa una fila recién creada0 &e produce este e+ento siempre 1ue el usuario elimina una fila 4aciendo clic en un encabe2ado de fila . presionando la tecla &*P?0
Copiar código
Visual Basic
Private Sub dataGridiew12Dser#eletin*3ow$yal sender !s @b(ectA 2 yal e !s System.Windows.Forms.#ataGridiew3owCancelEvent!r*s% 2 ?andles dataGridiew1.Dser#eletin*3ow I) e.3ow.Inde+ 0 Me.customers.Count /hen & I) the user has deleted an e+istin* rowA remove the & correspondin* Customer ob(ect )rom the data store. Me.customers.3emove!t$e.3ow.Inde+% End I) I) e.3ow.Inde+ - Me.rowInEdit /hen & I) the user has deleted a newly created rowA release & the correspondin* Customer ob(ect. Me.rowInEdit - ,1 Me.customerInEdit - "othin* End I) End Sub
C#
Copiar código
private void dataGridiew12Dser#eletin*3ow$ob(ect senderA System.Windows.Forms.#ataGridiew3owCancelEvent!r*s e% 9 i) $e.3ow.Inde+ 0 this.customers.Count% 9 :: I) the user has deleted an e+istin* rowA remove the :: correspondin* Customer ob(ect )rom the data store. this.customers.3emove!t$e.3ow.Inde+%7 = i) $e.3ow.Inde+ -- this.rowInEdit% 9 :: I) the user has deleted a newly created rowA release :: the correspondin* Customer ob(ect. this.rowInEdit - ,17 this.customerInEdit - null7 = = 790 5mplemente una clase Customers simple para representar los elementos de datos utili2ados por este ejemplo de código0
Visual Basic
Copiar código
Public Class Customer Private company"amealue !s Strin* Private contact"amealue !s Strin* Public Sub "ew$% & 'eave )ields empty. End Sub Public Sub "ew$yal company"ame !s Strin*A yal contact"ame !s Strin*% company"amealue - company"ame contact"amealue - contact"ame
End Sub Public Property Company"ame$% !s Strin* Get 3eturn company"amealue End Get Set$yal value !s Strin*% company"amealue - value End Set End Property Public Property Contact"ame$% !s Strin* Get 3eturn contact"amealue End Get Set$yal value !s Strin*% contact"amealue - value End Set End Property End Class
C#
Copiar código
public class Customer 9 private Strin* company"amealue7 private Strin* contact"amealue7 public Customer$% 9 :: 'eave )ields empty. = public Customer$Strin* company"ameA Strin* contact"ame% 9 company"amealue - company"ame7 contact"amealue - contact"ame7 =
public Strin* Company"ame 9 *et 9 return company"amealue7 = set 9 company"amealue - value7 = = public Strin* Contact"ame 9 *et 9 return contact"amealue7 = set 9 contact"amealue - value7 = = = Pro(ar la aplicaci)n Puede comprobar el formulario para asegurarse de 1ue se comporta de la forma pre+ista0
Para compro(ar el formulario •
Compile . ejecute la aplicación0 parecer3 un control DataGridView rellenado con tres registros del cliente0 Puede modificar los +alores de +arias celdas de una fila . presionar dos +eces E&C en el modo de edición . una +e2 fuera de éste modo para in+ertir la fila completa a sus +alores originales0 Cuando modificaagrega o elimina filas del control- se modifican- agregan o eliminan objetos Customer del almacén de datos- también0
Pasos si'uientes Esta aplicación proporciona conocimientos b3sicos de los e+entos 1ue debe controlar para implementar el modo +irtual en el control DataGridView0 Puede mejorar esta aplicación b3sica de +arios maneras: •
5mplemente un almacén de datos 1ue almacena en memoria cac4é los +alores de una base de datos externa0 a cac4é recuperar3 . descartar3 +alores seg!n sea necesario de modo 1ue sólo contenga lo 1ue es necesario para la presentación a la +e2 1ue utili2a una pe1ue8a cantidad de memoria en el e1uipo cliente0
•
juste el rendimiento del almacén de datos en función de sus re1uisitos0 Por ejemplo- 1ui23 desee compensar las conexiones de red ralenti2adas en lugar de las limitaciones de memoria del e1uipo cliente utili2ando un tama8o ma.or de cac4é . minimi2ando el n!mero de consultas de base de datos0
Para obtener m3s información sobre cómo almacenar en memoria cac4é +alores de una base de datos externa- +ea Cómo: 5mplementar el modo +irtual con l a carga de datos %ust65n6Time en el control (ata,ridView de formularios Windows Forms0
Vea tam(i*n Tareas Cómo: 5mplementar el modo +irtual en el control (ata,ridView de formularios Windows Forms
Referencia (ata,ridView Virtualode CellValue
Conceptos Procedimientos recomendados para ajustar la escala del control (ata,ridView en formularios Windows Forms 5mplementar el modo +irtual mediante la carga de datos %ust65n6Time en el control (ata,ridView de formularios Windows Forms
+tros recursos juste del rendimiento del control (ata,ridView en formularios Windows Forms
Para reali2ar una sugerencia o comunicar un error sobre la .uda u otra función de este producto- +a.a al sitio Product Feedbac Center0