Creating Searchable Custom Data Grid In WPF

Introduction

This Custom Data Grid provides the feature of searching data of each cell's contents and setting the background and foreground color of the cell that satisfies the search criteria. The Custom Data Grid has some public properties that assist in finding the value of cells; it is given below.

  1. SearchTextBoxName (String): The name of the Text Box Control whose value is to be searched.
  2. Is EnableSearch (Boolean): enables the Data Grid to search for a value.
  3. SearchedValueBackGroundColor (Brush): sets the background color of the cell that contains the search data.
  4. SearchedValueForegroundColor (Brush): sets the foreground color of the cell that contains the search data.

I will now explain how to create the custom Data Grid by inheriting from the System Data Grid Control. I have taken a class and inherited the class from the system Data Grid and added some extra features to the custom data grid. Initialized the default value of some properties of my data grid class.
The procedure to create the custom searchable Data Grid is given below.

  1. Start Visual Studio; on the start page, create a new project. Select the class library template, then rename it to Searchable Data Grid.
  2. Rename the class 1 to Data Grid, then inherit it from System.Windows.Controls.DataGrid. Add some extra public properties to help the data grid to be searchable. Such as SearchTextbox, IsEnableSearch, SearchValueBackGroundColor, SearchValueForegGroundColor, and one more private property that I have not explained above is SearchTextBox.

    Example

    public string SearchTextBoxName { get; set; }
    public bool IsEnableSearch { get; set; }
    public System.Windows.Media.Brush SearchedValueBackGroundColor { get; set; }
    public System.Windows.Media.Brush SearchedValueForeGroundColor { get; set; }
    private TextBox SearchTextBox { get; set; }
    
  3. In the default constructor of the initialization of the properties, set the default value of the properties.
    Example
    public SearchableDataGrid()
    {
        this.IsEnableSearch = false;
        this.SearchedValueBackGroundColor = System.Windows.Media.Brushes.Yellow;
        this.SearchedValueForeGroundColor = System.Windows.Media.Brushes.Gray;
    }
    
  4. Using the System.Windows.Media.VisualTreeHelper class, find the text box that exists in the parent controls of your data, whose value is to be searched in the data grid . The following coded helps to find the value of the TextBox.
    public static IEnumerable<T> FindVisualChildren<T>(DependencyObject ParentControl) where T : DependencyObject
    {
        if (ParentControl != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(ParentControl); i++)
            {
                DependencyObject ChildControl = VisualTreeHelper.GetChild(ParentControl, i);
                if (ChildControl != null && ChildControl is T)
                {
                    yield return (T)ChildControl;
                }
                foreach (T ChildOfChildControl in FindVisualChildren<T>(ChildControl))
                {
                    yield return ChildOfChildControl;
                }
            }
        }
    }
    
  5. The preceding function searched the child available in the container.
  6. Override the OnItemsSourceChanged function of the base class; that means "System.Windows.Controls.DataGrid". Call the function mentioned above (FindVisualChildren) that will use the reference of the text box controls whose text is to be searched in the data grid and add the Text change event handler to your TextBox.
    Example
    protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue)
    {
        // Code searches the TextBox control that exists in the parent of the DataGrid
        base.OnItemsSourceChanged(oldValue, newValue);
        if (this.IsEnableSearch == true && !string.IsNullOrEmpty(this.SearchTextBoxName))
        {
            foreach (TextBox tb in FindVisualChildren<TextBox>(this.Parent))
            {
                if (this.SearchTextBoxName == tb.Name)
                {
                    this.SearchTextBox = tb;
                    this.SearchTextBox.TextChanged += new TextChangedEventHandler(SearchTextBox_TextChanged);
                }
            }
        }
    }
    
  7. The TextChange event of your data grid TextBox finds the search value from each cell of your DataGrid view. If the condition is satisfied, then it sets the foreground and background colors of your DataGrid View.
    private void SearchTextBox_TextChanged(object sender, RoutedEventArgs e)
    {
        TextBox TB = (TextBox)sender;
        foreach (DataGridColumn DGC in this.Columns)
        {
            for (int ind = 0; ind < this.Items.Count; ind++)
            {
                FrameworkElement FE = DGC.GetCellContent(this.Items[ind]);
                
                if (FE != null && FE.GetType().Name == "TextBlock")
                {
                    TextBlock TX = (TextBlock)FE;
                    
                    if (TX != null)
                    {
                        if (!string.IsNullOrEmpty(TB.Text) && TX.Text.Contains(TB.Text))
                        {
                            System.Windows.Media.BrushConverter BC = new System.Windows.Media.BrushConverter();
                            TX.Background = this.SearchedValueBackGroundColor;
                            TX.Foreground = this.SearchedValueForeGroundColor;
                        }
                        else
                        {
                            TX.Background = System.Windows.Media.Brushes.White;
                            TX.Foreground = System.Windows.Media.Brushes.Black;
                        }
                    }
                }
            }
        }
    }
    
    The code mentioned above will help you to create a custom Data Grid Control. If you have any queries, then feel free to comment, and if this solves your problem, then please don't forget to like this article.


Recommended Free Ebook
Similar Articles