Cómo: Validar datos cuando se agrega una fila nueva a un control ListObject

Los usuarios pueden agregar filas nuevas a un control ListObject que está enlazado a datos. Puede validar los datos del usuario antes de confirmar los cambios realizados en el origen de datos.

Se aplica a: la información de este tema se aplica a los proyectos de nivel de documento y los proyectos de nivel de aplicación para Excel 2007 y Excel 2010. Para obtener más información, vea Características disponibles por aplicación y tipo de proyecto de Office.

Validación de datos

Siempre que se agrega una fila a un control ListObject enlazado a datos, se produce el evento BeforeAddDataBoundRow. Puede controlar este evento para realizar la validación de datos. Por ejemplo, si la aplicación requiere que únicamente los empleados con edades comprendidas entre 18 y 65 se puedan agregar al origen de datos, puede comprobar que la edad escrita se encuentre dentro de ese intervalo antes de agregar la fila.

Nota

Siempre deben comprobarse los datos proporcionados por el usuario en el servidor, además de en el cliente. Para obtener más información, vea Aplicaciones cliente seguras (ADO.NET).

Para validar los datos cuando se agrega una nueva fila a un control ListObject enlazado a datos

  1. Cree variables para el id. y el objeto DataTable en el nivel de clase.

    Dim id As Integer = 0
    Dim employeeTable As System.Data.DataTable
    
    private int id = 0;
    private System.Data.DataTable employeeTable;
    
  2. Cree un nuevo objeto DataTable y agregue columnas y datos de ejemplo en el controlador de eventos Startup de la clase Sheet1 (si es un proyecto en el nivel del documento) o la clase ThisAddIn (si es un proyecto en el nivel de la aplicación).

    employeeTable = New System.Data.DataTable("Employees")
    
    Dim column As System.Data.DataColumn = _
        employeeTable.Columns.Add("Id", GetType(Int32))
    column.AllowDBNull = False
    
    employeeTable.Columns.Add("FirstName", GetType(String))
    employeeTable.Columns.Add("LastName", GetType(String))
    employeeTable.Columns.Add("Age", GetType(Int32))
    
    employeeTable.Rows.Add(id, "Nancy", "Anderson", 56)
    employeeTable.Rows.Add(id, "Robert", "Brown", 44)
    id += 1
    
    list1.SetDataBinding(employeeTable, "", "FirstName", "LastName", "Age")
    
    employeeTable = new System.Data.DataTable("Employees");
    
    System.Data.DataColumn column = employeeTable.Columns.Add
        ("Id", typeof(int));
    column.AllowDBNull = false;
    
    employeeTable.Columns.Add("FirstName", typeof(string));
    employeeTable.Columns.Add("LastName", typeof(string));
    employeeTable.Columns.Add("Age", typeof(int));
    
    employeeTable.Rows.Add(id, "Nancy", "Anderson", "56");
    employeeTable.Rows.Add(id, "Robert", "Brown", "44");
    id++;
    
    list1.SetDataBinding(employeeTable, "", "FirstName", "LastName", "Age");
    
    list1.BeforeAddDataBoundRow +=new Microsoft.Office.Tools.Excel.
        BeforeAddDataBoundRowEventHandler(list1_BeforeAddDataBoundRow);
    
  3. Agregue código al controlador de eventos list1_BeforeAddDataBoundRow para comprobar si la edad escrita está comprendida en el intervalo de valores aceptados:

    Private Sub list1_BeforeAddDataBoundRow(ByVal sender As Object, ByVal e As  _
        Microsoft.Office.Tools.Excel.BeforeAddDataBoundRowEventArgs) _
        Handles list1.BeforeAddDataBoundRow
    
        Dim row As System.Data.DataRow = (CType(e.Item, System.Data.DataRowView)).Row
    
        If Not row("Age") Is Nothing And Not row("Age") Is Convert.DBNull Then
    
            Dim ageEntered As Integer = CType(row("Age"), Int32)
    
            If ageEntered < 21 Or ageEntered > 65 Then
                System.Windows.Forms.MessageBox.Show _
                    ("Age must be between 21 and 65. The row cannot be added.")
                e.Cancel = True
                Return
            End If
    
            row("ID") = id
            id += 1
    
        Else
            System.Windows.Forms.MessageBox.Show("You must enter an age.")
            e.Cancel = True
        End If
    End Sub
    
    private void list1_BeforeAddDataBoundRow(object sender,
        Microsoft.Office.Tools.Excel.BeforeAddDataBoundRowEventArgs e)
    {
        System.Data.DataRow row = ((System.Data.DataRowView)e.Item).Row;
    
        if (row["Age"] != null && row["Age"] != Convert.DBNull)
        {
            int ageEntered = (int)row["Age"];
    
            if (ageEntered < 21 || ageEntered > 65)
            {
                System.Windows.Forms.MessageBox.Show
                    ("Age must be between 21 and 65. The row cannot be added.");
                e.Cancel = true;
                return;
            }
            row["ID"] = id;
            id++;
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("You must enter an age.");
            e.Cancel = true;
        }
    }
    

Compilar el código

Este ejemplo de código supone que existe un control ListObject denominado list1 en la hoja de cálculo en la que aparece este código.

Vea también

Tareas

Cómo: Asignar columnas ListObject a datos

Conceptos

Ampliar documentos de Word y libros de Excel en complementos en el nivel de la aplicación en tiempo de ejecución

Agregar controles a documentos de Office en tiempo de ejecución

ListObject (Control)

Automatizar Excel usando objetos extendidos

Otros recursos

Controles en documentos de Office