How to loop through two GridViews to find the same values? C#
<p>I have two GridViews on my page - <code>grvBookCategories</code> shows categories of one particular book and <code>grvCategories</code> contains all possible categories for library. <code>grvBookCategories</code> is shown when page loads and <code>grvCategories</code> is fired on button click. There is checkbox <code>cbxGrvCategories</code> in ItemTemplate of <code>grvCategories</code>.</p>

<p>Question is - how to loop through those two GridViews to find the same values in both of them (both contain column with category name)? If there is a match - corresponding checkbox should be checked. For example - if there are 3 rows in <code>grvBookCategories</code> then 3 checkboxes should be also checked in <code>grvCategories</code>.</p>

<p>I've tried to do that using grvCategories_RowDataBound event and foreach loops but results are not exactly correct. The problem is when there is a match in the last  <code>grvCategories</code> row. In such case checkbox in that row in never checked, for all other rows results are fine. </p>

<pre><code>protected void grvCategories_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    string rowcValue = "";
    string rowbcValue = "";
    CheckBox cbx = new CheckBox();
    foreach (GridViewRow rowc in grvCategories.Rows)
    {
      if (rowc.RowType == DataControlRowType.DataRow)
      {
        rowcValue = rowc.Cells[2].Text;
        cbx = (CheckBox)rowc.Cells[3].FindControl("cbxGrvCategories");
        foreach (GridViewRow rowbc in grvBookCategories.Rows)
        {
          if (rowbc.RowType == DataControlRowType.DataRow)
          {
            rowbcValue = rowbc.Cells[1].Text;
            if (rowcValue.Equals(rowbcValue))
            {
              cbx.Checked = true;
              break;
            }
            else
            {
              cbx.Checked = false;
            }
          }
        }
      }
    }
  }
}
</code></pre>

<p>Thanks for any help in advance!</p>