Search code examples
c#winformsdata-bindingdatagridviewdatasource

DataGridView filtering method does not work correctly when a button is clicked


I know I asked this question already many times, but I did not get answer which can help me.

Please, need advice I already trying to do this 1 week or more.

I have a user control where my DataGrid is. There is a toolBar with a button that opens a Find form that has one button and one textBox. On this button click, I call method Search() like this :

private void btnFind_Click_1(object sender, EventArgs e)
{
    Inventory i = new Inventory();
    i.Search(txtFind.Text);
}

and this is how the method Search works :

public void Search(string searchWord) 
{
    AcidDBDataContext db = new AcidDBDataContext();
    var q = db.ProcSearch(searchWord);
    dgvInventory.DataSource = q;
}

This method works fine in inventory but when I click btnFind, it doing nothing, I used a debugger and saw that query is executing correctly and gets rows from table.

Problem is on this line : dgvInventory.DataSource = q;

I'm using C# WinForms and SQL Server 2008


Solution

  • You could use a BindingSource

    BindingSource bs = new BindingSource();
    

    and then in Search(string searchWord)

    //dgvInventory.DataSource = q;
    bs.DataSource = q;
    if (dgvInventory.DataSource == null)
        dgvInventory.DataSource = bs;
    else
        bs.ResetBindings(false);