Click here to Skip to main content
15,907,001 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Okay so I have a data gridview which will not only just display the data but will also allow me to filter the data.
You can get an example of how the filter will look like on the gridview by looking at the following picture. Gridview Picture

you can also read about it through here Building a Drop-Down Filter List for a DataGridView Column Header Cell[^]

Now with that explained,
the issue i am having is that it works perfectly only if I bind data through visual studio by going to "Server Explorer" and basically auto binding the data without having to write a query in the back.


What I want to do is to find out a way to add the details ( the query etc) by myself.
The reason I want to do this is because my whole app is kinda done in a way where database is connected to gridviews etc programatically.

For example here is a normal datagridview file that I use in my project
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Call_Logger
{
    public partial class Dashboard : Form
    {
        private OleDbConnection con = new OleDbConnection();

        public Dashboard()
        {
            InitializeComponent();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ToString();
        }

        private void btn_LoadTable_Click(object sender, EventArgs e)
        {
            try
            {

                con.Open();
                OleDbCommand command = new OleDbCommand();
                command.Connection = con;
                command.CommandText = ("select * from LogCall");
                command.ExecuteNonQuery();

                OleDbDataAdapter da = new OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;

                con.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error " + ex);
            }
        }

        private void btn_AddRecords_Click(object sender, EventArgs e)
        {
            this.Hide();
            AddingFunctionality Add = new AddingFunctionality();
            Add.ShowDialog();
            
        }

        private void btn_Edit_Click(object sender, EventArgs e)
        {
            this.Hide();
            Edit Add = new Edit();
            Add.ShowDialog();
        }

        private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
            AddCallStatus Add = new AddCallStatus();
            Add.ShowDialog();
        }

        private void editExistingValueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
            EditCallType Add = new EditCallType();
            Add.ShowDialog();
        }

      
        private void addNewToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Hide();
            LocationAdd Add = new LocationAdd();
            Add.ShowDialog();
        }

        private void editExistingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
            EditLocation Add = new EditLocation();
            Add.ShowDialog();
        }

        private void addNewToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.Hide();
            AddCallStatus Add = new AddCallStatus();
            Add.ShowDialog();
        }

        private void editExistingValueToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Hide();
            EditCallSubjects Add = new EditCallSubjects();
            Add.ShowDialog();
        }

        
        

       

       
    }
}


And, here is the code for the datagridview with the feature of Auto-Filtering

C#
using DataGridViewAutoFilter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DesignerSetupDemo
{
    public partial class DesignerSetupForm : Form
    {
        public DesignerSetupForm()
        {
            InitializeComponent();
        }

        private void DesignerSetupForm_Load(object sender, EventArgs e)
        {
            // Load the sample data and resize the columns based on their contents.
            this.newDataSet.ReadXml(@"..\..\..\..\..\TestData.xml");
            this.dataGridView1.AutoResizeColumns();
        }

        // Displays the drop-down list when the user presses 
        // ALT+DOWN ARROW or ALT+UP ARROW.
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt && (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up))
            {
                DataGridViewAutoFilterColumnHeaderCell filterCell =
                    dataGridView1.CurrentCell.OwningColumn.HeaderCell as
                    DataGridViewAutoFilterColumnHeaderCell;
                if (filterCell != null)
                {
                    filterCell.ShowDropDownList();
                    e.Handled = true;
                }
            }
        }

        // Updates the filter status label. 
        private void dataGridView1_DataBindingComplete(object sender,
            DataGridViewBindingCompleteEventArgs e)
        {
            String filterStatus = DataGridViewAutoFilterColumnHeaderCell
                .GetFilterStatus(dataGridView1);
            if (String.IsNullOrEmpty(filterStatus))
            {
                showAllLabel.Visible = false;
                filterStatusLabel.Visible = false;
            }
            else
            {
                showAllLabel.Visible = true;
                filterStatusLabel.Visible = true;
                filterStatusLabel.Text = filterStatus;
            }
        }

        // Clears the filter when the user clicks the "Show All" link
        // or presses ALT+A. 
        private void showAllLabel_Click(object sender, EventArgs e)
        {
            DataGridViewAutoFilterColumnHeaderCell.RemoveFilter(dataGridView1);
        }

    }
}



I need to convert the code of the 2nd example to the code of the 1st example

What I have tried:

Actually the thing is that the results shown in the database does not include the newly added values.
Posted
Updated 3-Jun-16 8:16am
v2
Comments
RickZeeland 6-Jun-16 13:46pm    
Use the CurrencyManager. Maybe this article "Implementing complex data binding in custom controls" can be of help: http://www.codeproject.com/Articles/15396/Implementing-complex-data-binding-in-custom-contro

1 solution

Here is a bit of code from my WinForms project which might give you some ideas.
It shows a "filter form" and makes use of Linq and BindingList.
C#
// R-mouse button shows context menu, handle click here.
private void ContextMenuClick(object sender, EventArgs e)
{
    // Filter on column value.
    var colName = this.dataGridViewMaster.Columns[this.clickedColumn].Name;
    var filter = this.FilterInit(this.clickedColumn, this.clickedRow);
    this.FilterDataGrid(colName, filter);
}

// Handle filtering dependent on datatype of column.
private string FilterInit(int columnIndex, int rowIndex)
{
    string filter = string.Empty;

    switch (this.dataGridViewMaster.Columns[columnIndex].Name)
    {
        case "Date":
            // Code for DateTime.
            var cellValue1 = (DateTime)this.dataGridViewMaster.Rows[rowIndex].Cells[columnIndex].Value;

            if (cellValue1 != null)
            {
                filter = cellValue1.Date.ToString(CultureInfo.CurrentCulture);
            }

            break;
        default:
            var cellValue2 = this.dataGridViewMaster.Rows[rowIndex].Cells[columnIndex].Value;

            if (cellValue2 != null)
            {
                filter = cellValue2.ToString();
            }

            break;
    }

    return filter;
}

/// <summary>
/// Show the filter form which allows to edit the filter string.
/// </summary>
/// <param name="columnName">The selected column name.</param>
/// <param name="filterString">The filter string.</param>
private void FilterDataGrid(string columnName, string filterString)
{
    var filterForm = new FormFilter(filterString);
    var result = filterForm.ShowDialog();

    if (result == DialogResult.OK)
    {
        var filter = filterForm.textBoxFilter.Text;
        var ignoreCase = filterForm.checkBoxCase.Checked;
        this.dataGridViewMaster.Columns.Clear();

        // Define a Linq filter expression here ...
        // funcFilter
        // this.masterBindingList = new BindingList<RequestsType>(this.masterBindingList.Where(funcFilter).ToList());

        //bool flag = false;
        //this.masterBindingList = new BindingList<RequestsType>(this.masterBindingList.Where(m => (m.Equals(flag))).ToList());

        //var q = from w in this.masterBindingList where w.Exceptional select w;
        //this.dataGridViewMaster.DataSource = q;

        this.dataGridViewMaster.DataSource = this.masterBindingList;
        this.SetDataGrid();
    }
    else if (result == DialogResult.Cancel)
    {
        // Clear filter.
        this.SetDataSource();
    }
}
 
Share this answer
 
Comments
Member 12087138 6-Jun-16 7:26am    
Thanks for the answer but my issue is not in the filtering of the data but the fact that the data that is displayed in my database is an old instance of the database table with only 3 rows.

Whereas I have added more data to the table (around 7 rows more) and it still shows the 3 rows

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900