Search code examples
c#datagridviewtextboxdatarow

C# - If DataGridView contains searched word, export these lines to new DataGridView


I have a DataGridView. I want to do this; I will use a textbox. After the DataGridView filling, I will fill my textbox with a word and if my DataGridView's any line contains this word, I will export these lines to a new DataGridView. Let me explain. My DataGridView looks like that;

              Column1                  Column2           Column3
  -------------------------------------------------------------------
         albania algeria                800               55.32
      antarctica argentina              950                         
         brazil bulgaria                25                77
        india indonesia                 30000             78.53
        argentina  iran                 18                0.01
        moldova mongolia                25854             77.50

And imagine that I have a textbox. Let's say I wrote Argentina in my textbox. After this operation my new DataGridView looks like that;

             Column1                Column2                Column3
     ------------------------------------------------------------------
      antarctica argentina            950                         
      argentina iran                  18                     0.01

Note: I couldn't produce any idea for it, sorry.


Solution

  • Assuming you really need two DataGridViews:

        private void button2_Click(object sender, System.EventArgs e)
        {
            dataGridView2.Rows.Clear();
    
            var filterText = textBox1.Text;
    
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (Convert.ToString(row.Cells[0].Value).Contains(filterText))
                {
                    var filteredRow = (DataGridViewRow)row.Clone();
    
                    //Copy values from one DataGridViewRow to another
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        filteredRow.Cells[cell.ColumnIndex].Value = cell.Value;
                    }
    
                    dataGridView2.Rows.Add(filteredRow);
                }
            }
        }