[TextBox, DataGridView, BindingSource] Search as you type

I created my own search as you type feature by using TextBox, DataGridView, and BindingSource. It's very simple to implement. Here is the code:

PS: I already have a TextBox & a DataGridView on the form.

public partial class LookupTable : Form
  // This will be the data source of the DataGridView.
  BindingSource oBindingSource = new BindingSource();
  CallerDTO caller = null;
  public LookupTable(DataTable sourceData, CallerDTO sourceDTO)
    caller = sourceDTO;
    // Assign the DataTable to our BindingSource object.
    oBindingSource.DataSource = sourceData;
  private void LookupTable_Load(object sender, EventArgs e)
    toolTipFind.SetToolTip(textBoxFind, "You can search by Name or by Code.");
    // Assign the BindingSource object to the DataGridView.
    dataGridViewResult.DataSource = oBindingSource;
  private void textBoxFind_TextChanged(object sender, EventArgs e)
    TextBox oTextBox = sender as TextBox;
    // Here is the key of the whole "Search As You Type" function.
    oBindingSource.Filter = "NAME LIKE '%" + oTextBox.Text + "%' OR CODE LIKE '%" + oTextBox.Text + "%'";
  private void dataGridViewResult_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
    // Here I need to send back the value that user clicked on.
    caller.StringResult = dataGridViewResult.Rows[e.RowIndex].Cells[1].Value.ToString();
    // This is just a public method for me to do something after user clicking.


No comments:

Post a Comment