Reputation: 3
As the question ask above, I have create ComboBox
dynamically from code behind.
The code as below (this code is inside BtnAddComboBox_Click
)
Grid grid = new Grid();
comboBox = new ComboBox();
comboBox.ItemsSource = salesman2;
comboBox.Name = "cbSalesman";
Button button = new Button();
button.Width = 50;
button.Name = "btnDelete";
button.Height = 30;
button.Background = Brushes.Transparent;
button.BorderBrush = Brushes.Transparent;
button.Click += new RoutedEventHandler(btnDeleteCB_Click);
grid.Children.Add(comboBox);
grid.Children.Add(button);
stackPanel.Children.Add(grid);
And I have a Button
name AddComboBox
at my XAML (the blue button). when user click on the button. the New ComboBox will be added along with the DELETE BUTTON
named btnDelete
beside it. so that's means every comboBox will have its own delete button. it does not have max number of ComboBox
so it will keep adding the new ComboBox whenever user click the button.
The problem is when I click the btnDelete
. It will delete all the comboBox added (since it have the same name I guess)
This is my delete method:
private void btnDeleteCB_Click(object sender, RoutedEventArgs e)
{
StackPanel stackPanel = FindChildControl<StackPanel>(this,"spSalesmanCombobox") as StackPanel;
stackPanel.Children.Remove(comboBox);
}
what I want is when I click the btnDelete
, only the ComboBox
beside it will deleted. How can I do that ? Is it possible to do it ?
I want to the delete the ComboBox
itself. not the selected item / items inside it.
Upvotes: 0
Views: 259
Reputation: 2739
You can try something like this. It will delete the Grid in which the Combobox and the Button is in. While leaving all others untouched. (I couldnt verify this code as i dont have an IDE right now)
private void btnDeleteCB_Click(object sender, RoutedEventArgs e)
{
Grid grd = (sender as Button).Parent as Grid; //sender is button -> Parent is your grid
stackPanel.Children.Remove(grd); //remove that grid from the Stackpanel that contans them all
}
Generally i would like to mention that WPF is designt to be used with MVVM where you do not have to manipulate the gui like this. Its a little bit harder to learn than the Windows forms way using the codebehind but will payoff after a while
Upvotes: 1