I have combobox with numbers from 1 to 10 and depending on the user the choice makes so many of my controls should be displayed in my form. The first time the form loads the combo box, it matters one, and there is only one user-defined petdetails control in the grid (which adds only one row and additional columns when changes are made). My program works fine to such an extent, but as soon as the user adds more and decreases for some reason, the columns are deleted, but in the last column the controls overlap (for example, the user selects 6, 6 controls and once he changes the value in the field with with a list of up to 3, only 3 columns remain, but in the third column I see that the 5.6 user controls are full). I insert my code here, any help would be greatly appreciated.
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 > grdCols) for (int j = grdCols+1 ; j <= 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 < grdCols) for (int j = grdCols; j > i; j--) { PetDetails petdetails = new PetDetails(); petdetails.Name = "petDetails" + j; grdPetDetails.Children.Remove(petdetails); grdPetDetails.ColumnDefinitions.RemoveAt(j - 1); } }
I delete the controls first and then the column definitions, but then I canβt understand why this is happening.
Thanks in advance.
source share