Pergunta

I've been trying to make a search function for a dataTable. My problem is that the first row of the table is ALWAYS within the filtered rows, even when the boolean column is actually changed to a zero. Here is my search code:

private void buscar()
    {
        DataTable dataTable;
        if (!verTodos)
        {
            dataTable = DBHelper.Instance.ProductosConStock();
        }
        else
        {
            dataTable = DBHelper.Instance.ProductosTodos();
        }
        dataGridProductos.DataSource = dataTable.DefaultView;
        foreach (DataGridViewRow row in dataGridProductos.Rows)
        {
            if (row.Cells[0].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()) ||
                row.Cells[1].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()) ||
                row.Cells[2].Value.ToString().ToUpper().Contains(txtBusqueda.Text.ToString().ToUpper()))
            {
                row.Cells[4].Value = 1;
            }
            else
            {
                row.Cells[4].Value = 0;
            }
        }
        dataTable.DefaultView.RowFilter = "mostrar = 1";
    }
Foi útil?

Solução

Try creating a DataView from your datatable and run the filter based on that. Below is a quick example i tried and it works fine.

        DataTable dt = new DataTable();

        dt.Columns.Add("bool", typeof(Boolean));

        dt.Rows.Add(true);
        dt.Rows.Add(false);
        dt.Rows.Add(true);

        DataView dv = new DataView(dt);

        dv.RowFilter = "bool = 1";

        foreach (DataRowView drv in dv)
        {
            Console.WriteLine(drv[0].ToString());
        }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top