How to clean the contents of a DataGrid?

2

I have a (WPF) window and a C # code that contains the following One button:

<Button x:Name="btnBuscar" Content="Buscar por" HorizontalAlignment="Left" Margin="157,10,0,0" VerticalAlignment="Top" Width="85" Height="30" Click="btnBuscar_Click"/>

a comboBox:

<ComboBox x:Name="cmbBuscarPor" HorizontalAlignment="Left" Margin="247,10,0,0" VerticalAlignment="Top" Width="120" Height="30">
        <ComboBoxItem Content="Nombre"/>
        <ComboBoxItem Content="Apellido paterno"/>
        <ComboBoxItem Content="Puesto"/>
    </ComboBox>

a Texbox:

<TextBox x:Name="tbBusqueda" Height="30" Margin="0,10,160,0" TextWrapping="Wrap" Text="Ingrese texto" VerticalAlignment="Top" VerticalContentAlignment="Center" HorizontalAlignment="Right" Width="230" GotFocus="tbBusqueda_GotFocus"/>

a DataGrid somewhat similar to the following (more columns):

<DataGrid x:Name="dataGridUsuarios" CanUserAddRows="True" HorizontalAlignment="Left" Height="230" Margin="10,110,0,0" VerticalAlignment="Top" Width="742" KeyUp="dataGridUsuarios_KeyUp" MouseLeftButtonUp="dataGridUsuarios_MouseLeftButtonUp">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=idUsuario}" ClipboardContentBinding="{x:Null}"  Header="idUsuario" HeaderStringFormat="idUsuario" Visibility="Hidden"/>
            <DataGridTextColumn Binding="{Binding Path=Nombre}" ClipboardContentBinding="{x:Null}" Header="Nombre"  HeaderStringFormat="Nombre" Width="105"/>
            <DataGridTextColumn Binding="{Binding Path=ApellidoP}" ClipboardContentBinding="{x:Null}" Header="Apellido Paterno" HeaderStringFormat="ApellidoP" Width="105"/>
            <DataGridTextColumn Binding="{Binding Path=ApellidoM}" ClipboardContentBinding="{x:Null}" Header="Apellido materno" HeaderStringFormat="ApellidoM" Width="105"/>
            <DataGridTextColumn Binding="{Binding Path=Sexo}" ClipboardContentBinding="{x:Null}" Header="Sexo" HeaderStringFormat="Sexo" Width="105"/>
        </DataGrid.Columns>

The DataGrid is filled when starting with the registration of a database with the following method

public void llenadoDataGrid()
    {
        String consulta = "select idUsuario,Nombre,ApellidoP ,ApellidoM ,Sexo,Telefono,Edad,Puesto,NombreUsuario,Contraseña from usuarios;";
        SqlDataAdapter dataAdapter = new SqlDataAdapter(consulta, new BaseDeDatos().obtenerConexion());
        DataSet ds = new DataSet();
        dataAdapter.Fill(ds);
        DataTableCollection collection = ds.Tables;
        DataTable table = collection[0];

        foreach (DataRow row in table.Rows)
        {
            var data = new PruebaDeLLenadoDataGrid {idUsuario = row["idUsuario"].ToString(), Nombre = row["Nombre"].ToString(),
                ApellidoP = row["ApellidoP"].ToString(), ApellidoM = row["ApellidoM"].ToString(),
                Sexo = row["Sexo"].ToString()
            };
            dataGridUsuarios.Items.Add(data);
        }
    }

I use the following class that I was advised to fill the data grid with the previous method

class PruebaDeLLenadoDataGrid
{
    public String idUsuario { get; set; }
    public String Nombre { get; set; }
    public String ApellidoP { get; set; }
    public String ApellidoM { get; set; }
    public String Sexo { get; set; }
}

when I click on the search button, I do the following

private void btnBuscar_Click(object sender, RoutedEventArgs e)
    {
        String dato = tbBusqueda.Text;
        int index = cmbBuscarPor.SelectedIndex;
        if (dato != ""  && dato != "Ingrese texto" && index != -1)
        {
            dataGridBuscador(index, dato);
        }
        else
        {
            if (index == -1)
            {
                MessageBox.Show("seleccione una opcion de busqueda");
            }
            MessageBox.Show("Ingrese un texto para la busqueda");
        }
        MessageBox.Show("busqueda valor index "+index);
    }

the search is done with the dataGridBuscador method in which I send the index to use each of the different searches and the problem lies with who since doing this performs the search and shows it in the dataGridUsuarios puts me a new row based on the previous ones instead of just showing the row or rows of the search p>

        private void llenadoConBusqueda(int opcion,String dato)
    {
        String prueba = "";
        switch (opcion)
        {
            case 0:
                prueba = "select idUsuario,Nombre,ApellidoP ,ApellidoM ,Sexo from usuarios where Nombre ='"+dato+"';";
                break;
            case 1:
                prueba = "select idUsuario,Nombre,ApellidoP ,ApellidoM ,Sexo from usuarios where ApellidoP ='" + dato + "';";
                break;
        }
        SqlDataAdapter dataAdapter = new SqlDataAdapter(prueba, new BaseDeDatos().obtenerConexion());
        DataSet ds = new DataSet();
        dataAdapter.Fill(ds);
        DataTableCollection collection = ds.Tables;
        DataTable table = collection[0];

        foreach (DataRow row in table.Rows)
        {
            var data = new PruebaDeLLenadoDataGrid
            {
                idUsuario = row["idUsuario"].ToString(),
                Nombre = row["Nombre"].ToString(),
                ApellidoP = row["ApellidoP"].ToString(),
                ApellidoM = row["ApellidoM"].ToString(),
                Sexo = row["Sexo"].ToString()
            };
            dataGridUsuarios.Items.Add(data);
        }
    }
    
asked by Richard Yordy 09.04.2018 в 07:38
source

1 answer

4

It all depends on how you are filling in the data in DataGrid . If, as is your case, you use:

dataGrid.Items.Add(someObject);

To clean it you can use the method Clear of Items :

dataGridUsuarios.Items.Clear();

If you use databinding by adding the data in ItemsSource :

dataGrid.ItemsSource = colleccion;

what you should do is put ItemsSource to null .

    
answered by 09.04.2018 / 09:23
source