Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Actualización: noviembre 2007
Nota: |
|---|
Aunque el control DataGridView viene a reemplazar y a agregar funcionalidad al control DataGrid, este control DataGrid se conserva a efectos de compatibilidad con versiones anteriores y para uso futuro, según sea el caso. Para obtener más información, vea Diferencias entre los controles DataGridView y DataGrid de formularios Windows Forms. |
Existen dos formas de validar los datos introducidos para el control DataGrid de formularios Windows Forms. Si el usuario intenta introducir un valor cuyo tipo de datos no es aceptable para la celda, por ejemplo, una cadena en un entero, el nuevo valor no válido se reemplaza con el valor anterior. Esta clase de validación de los datos introducidos se realiza automáticamente y no se puede personalizar.
La otra forma de validar los datos introducidos puede utilizarse para rechazar todos los datos que no sean aceptables, por ejemplo un valor 0 en un campo cuyo valor debe ser mayor o igual que 1, o una cadena incorrecta. Para ello, en el conjunto de datos se escribe un controlador de eventos para el evento ColumnChanging o RowChanging. En el ejemplo siguiente se utiliza el evento ColumnChanging porque el valor que no es aceptable no se permite en la columna "Product" concretamente. Se podría utilizar el evento RowChanging para comprobar si el valor de una columna "End Date" es posterior al valor de la columna "Start Date" de la misma fila.
Para validar los datos introducidos por el usuario
Escriba código que controle el evento ColumnChanging para la tabla correspondiente. Cuando se detecte una entrada incorrecta, llame al método SetColumnError del objeto DataRow.
Private Sub Customers_ColumnChanging(ByVal sender As Object, _ ByVal e As System.Data.DataColumnChangeEventArgs) ' Only check for errors in the Product column If (e.Column.ColumnName.Equals("Product")) Then ' Do not allow "Automobile" as a product. If CType(e.ProposedValue, String) = "Automobile" Then Dim badValue As Object = e.ProposedValue e.ProposedValue = "Bad Data" e.Row.RowError = "The Product column contians an error" e.Row.SetColumnError(e.Column, "Product cannot be " & _ CType(badValue, String)) End If End If End Sub//Handle column changing events on the Customers table private void Customers_ColumnChanging(object sender, System.Data.DataColumnChangeEventArgs e) { //Only check for errors in the Product column if (e.Column.ColumnName.Equals("Product")) { //Do not allow "Automobile" as a product if (e.ProposedValue.Equals("Automobile")) { object badValue = e.ProposedValue; e.ProposedValue = "Bad Data"; e.Row.RowError = "The Product column contains an error"; e.Row.SetColumnError(e.Column, "Product cannot be " + badValue); } } }//Handle column changing events on the Customers table private void Customers_ColumnChanging(System.Object sender, System.Data.DataColumnChangeEventArgs e) { //Only check for errors in the Product column if ( e.get_Column().get_ColumnName().Equals("Product") ) { //Do not allow "Automobile" as a product if ( e.get_ProposedValue().Equals("Automobile") ) { System.Object badValue = e.get_ProposedValue(); e.set_ProposedValue("Bad Data"); e.get_Row().set_RowError("The Product column contains an error"); e.get_Row().SetColumnError(e.get_Column(), "Product cannot be " + badValue); } } }Conecte el controlador de eventos al evento.
Incluya el siguiente código en el evento Load del formulario o en su constructor.
' Assumes the grid is bound to a dataset called customersDataSet1 ' with a table called Customers. ' Put this code in the form's Load event or its constructor. AddHandler customersDataSet1.Tables("Customers").ColumnChanging, AddressOf Customers_ColumnChanging// Assumes the grid is bound to a dataset called customersDataSet1 // with a table called Customers. // Put this code in the form's Load event or its constructor. customersDataSet1.Tables["Customers"].ColumnChanging += new DataColumnChangeEventHandler(this.Customers_ColumnChanging);// Assumes the grid is bound to a dataset called customersDataSet1 // with a table called Customers // Put this code in the form's Load event or its constructor. customersDataSet1.get_Tables().get_Item("Customers").add_ColumnChanging( new DataColumnChangeEventHandler(this.Customers_ColumnChanging));
Nota: