title: dynamically removing columns from grid in wpf
body: <p>I have a combobox with numbers 1 to 10 and depending on the selection user makes that  that many user controls should be displayed on my form .The first time the form loads  combo box has value one and there is only one user control petdetails in the grid (which has only one row and additional columns are added as the changes are made). My program is working fine till this extent but once the user adds a higher and reduces for some reason columns are deleted but there is a overlapping of the controls in the last column.(For eg: User chose 6 ,6 controls are added and once he changes the value in combo box to 3 there are only 3 columns left but in the third column I can see the user controls 5,6 are over lapped).I am pasting my code here any help would be greatly appreciated.</p>
  
  <pre><code>private void cmbNoOfPets_SelectionChanged(object sender, SelectionChangedEventArgs e)
      {
  
          int i = Convert.ToInt32(((System.Windows.Controls.ContentControl)(cmbNoOfPets.SelectedValue)).Content);
          int grdCols=Convert.ToInt32(grdPetDetails .ColumnDefinitions .Count.ToString ()); 
          // check if the number of pets is more than the existing number in the grid if more start with adding at the next column
          // if less start from the last decreasing till the number of columns required
              if (i &gt; grdCols)
              for (int j = grdCols+1 ; j &lt;= i; j++)
              {
  
                  ColumnDefinition c = new ColumnDefinition();
                  c.Width = new GridLength(370, GridUnitType.Pixel);
                  grdPetDetails.ColumnDefinitions.Add  (c);
                  PetDetails petdetails = new PetDetails();
                  petdetails.Name = "petDetails" + j ;
                  string str="Pet Number " + j + ":";
                  petdetails.lblPetNumber.Content = str;
                  Grid.SetRow(petdetails, 1);
                  Grid.SetColumn(petdetails, j - 1);
                  grdPetDetails.Children.Add(petdetails);
  
             }
              else if (i &lt; grdCols)
  
                  for (int j = grdCols; j &gt; i; j--)
                  {
  
                      PetDetails petdetails = new PetDetails();
                      petdetails.Name = "petDetails" + j;
                      grdPetDetails.Children.Remove(petdetails);
                      grdPetDetails.ColumnDefinitions.RemoveAt(j - 1);
  
  
                  } 
  
       }
  </code></pre>
  
  <p>I am deleting the controls first and then the column definitions but then can't understand why this is happening.</p>
  
  <p>Thanks in advance.</p>