简体   繁体   中英

C# - How To Copy The Searched Rows In DataGridView To New DataGridView

I have a program, it's about foods and their calories. I'm showing datas in a DataGridView1. And I want to copy rows to a DataGridView2, If my DataGridView1 contains searched text in TextBox. My DataGridView1 looks like that:

                  Food                    Calorie
           ------------------------------------------
                 Bread                       80
                 Tea                         0
                 ...                         ...

So, it's my code:

      private void button5_Click(object sender, EventArgs e)
      {
          var searchedText = textBox1.Text;
          foreach(DataGridViewRow dgwr in dataGridView1.Rows)
          {
              if (Convert.ToString(dgwr.Cells[0].Value).Contains(searchedText))
              {
                  var filteredRow = (DataGridViewRow)dgwr.Clone();
                  foreach (DataGridViewCell mySearchedCells in dgwr.Cells)
                  {
                      filteredRow.Cells[mySearchedCells.ColumnIndex].Value = mySearchedCells.Value;
                  }
                  dataGridView2.Rows.Add(filteredRow);
              }
          }
      }

PS : It doesn't work and it doesn't give error.

OK, I solved. I changed all my DataGridViews' columns ReadOnly properties to false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM