In a few lines of code, we can convert a DataGridView control in a powerfull fully searchable control with dynamically generated filters for each column of field the DataGridView is binded to.
How does it work?
Screenshots
Demo Video
Some code:
/// <summary> /// Build texbox controls for dinamyc search form based on fields collection /// </summary> /// <param name="fields"></param> private void BuildControls(List<field> fields) { int top = 10; bool focused = false; #region Loop for each field foreach (field f in fields) { Label label = new Label(); label.Text = f.FriendlyName + ":"; label.Top = top; label.Left = 5; label.AutoSize = true; this.Controls.Add(label); TextBox textbox = new TextBox(); textbox.TextChanged += new EventHandler(textBox_TextChanged); textbox.Tag = f.Field; textbox.Top = top; textbox.Left = 68; textbox.Width = this.Width - 80; if (!focused) { textbox.Focus(); //the first control focused focused = true; } top += 35; this.Controls.Add(textbox); } #endregion this.Height = top + 30; }
// Raise event to parent form if textbox content changes private void textBox_TextChanged(object sender, EventArgs e) { if (TextChanged != null) TextChanged(GetFilterValues()); } #region Shortcuts private void frmSearch_KeyDown(object sender, KeyEventArgs e) { if ((e.KeyCode == Keys.Escape) || (e.KeyCode == Keys.Enter)) Close(); } #endregion
namespace dynamicGridFilter { /// <summary> /// This struct contains information about each field to be filtered along with filter value, if exists. /// </summary> public struct field { public string Field; public string FriendlyName; public string Value; } }
namespace dynamicGridFilter { public delegate void SearchContextChangedHandler(List<field> fields); }
Complete source code available to download:
What's next?!
If could have gone all the way up to creating a custom control that inherits from DataGridView and has all the logic embedded. Well, you have here all you need for doing it yourself, so don't call me lazy! :P
Comments are welcome!
Remember Me
a@href@title, b, em, i, strike, strong