Home > database >  Apply filter on multiple column in data table
Apply filter on multiple column in data table

Time:05-11

Code i am using

 (DataGridViewAllMusic.DataSource as DataTable).DefaultView.RowFilter = 
 string.Format("Title LIKE '%{0}%' or Artist LIKE '%{1}%' or Album LIKE '%{2}%' or 
 Comments LIKE '%{3}%' ",TextboxSearch.Text, TextboxSearch.Text, TextboxSearch.Text, 
 TextboxSearch.Text);

Working output:

suppose datagridview showing song information as (SongTitle on left and Artist on right)

Title & Artist

A Tender Life & Three Degrees

and i type Life in TextboxSearch the datagridview will show the song detail since word Life is found in DataTable column Title

Now if i search Degree, again Degree is found in DataTable column Artist so the datagridview will show the same result

Desired filter:

Now i also want to search the song in a way like the artist and song title together.

such that Three Degrees A Tender Life if i search this in TextboxSearch, the datagridview should also display the same result as displaying when searching the title or artist separately

CodePudding user response:

A special thanks to @dr.null . I found his vb.net code and used in c#. It works great!

Vb.net by dr.null

 var sb = new StringBuilder();
 var cols = new[] { "Title", "Artist" };
 var words = TextboxSearch.Text.Split(',').Where(x => x.Trim().Length > 0);

 for (var i = 0; i <= cols.Length - 1; i  )
 {
                               
    for (var j = 0; j <= words.Count() - 1; j  )
    {  
         sb.Append($"{cols[i].Trim()} LIKE ' 
         {words.ElementAt(j).Trim()}%'");
         if (j != words.Count() - 1)
            sb.Append(" OR ");
    }
     if (i != cols.Length - 1)
        sb.Append(" OR ");
 }
(DataGridViewAllMusicDark.DataSource as DataTable).DefaultView.RowFilter = 
sb.ToString();
  • Related