anita handa
anita handa

Reputation: 1

How to create a search textbox with datagridview bound to BindingSource in C#?

I wanna make a Search textbox on Data Grid View in C# and SQLServer, but datagridview bound to BindingSource. i try this code Not function.

private void ucObat_Load(object sender, EventArgs e)
        {
            db = new DbSIMP3Entities();
            tbObatBindingSource.DataSource = db.tbObats.ToList();
            tbSatuanBindingSource.DataSource = db.tbSatuans.ToList();
            tbKategoriBindingSource.DataSource = db.tbKategoris.ToList();
            tbMerkBindingSource.DataSource = db.tbMerks.ToList();

        }
private void txtSearch_Click(object sender, EventArgs e)
        {
            tbObatBindingSource.Filter = "NmObat like '&" + txtSearch.Text + "&'";
        }

Upvotes: 0

Views: 574

Answers (1)

Ryfcia
Ryfcia

Reputation: 457

BindingSource.Filter will work only when your datasource implements IBindingListView

Only underlying lists that implement the IBindingListView interface support filtering.

So, to make it work you've to change your underlying datasource.

If you don't wanna use DataView for some reason try using BindingSource itself as a datasource.

private BindingSource bs = new BindingSource();
private BindingList<ObatsEntity> initialObats = new BindingList<ObatsEntity>();

private void ucObat_Load(object sender, EventArgs e)
{
    db = new DbSIMP3Entities();
    initialObats = new BindingList<ObatsEntity>( db.tbObats.ToList() );
    bs.DataSource = initialObats;
    dataGridView.DataSource = bs;
}

private void txtSearch_Click(object sender, EventArgs e)
{
    var filteredObats = new BindingList<ObatsEntity>( initialObats.Where( o => o.NmObat == txtSearch.Text ).ToList() );
    bs.DataSource = filteredObats;
    bs.ResetBindings();
}

Upvotes: 1

Related Questions