Marina Marina - 1 month ago 19
C# Question

creating textbox when button click in WPF?

i already searched few stackoverflow threads related thisbut i have problem in code plz review my code and tell me where is the problem i am stuck and do not where is the problem i am new here please help me out

public partial class MainWindow : Window
{
Grid MainGrid = new Grid();
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
TextBox dynamicTextBox = new TextBox();
dynamicTextBox.Text = "Type Partnumber";
Grid.SetRow(dynamicTextBox, 1);
Grid.SetColumn(dynamicTextBox, 0);
this.MainGrid.Children.Add(dynamicTextBox);
}
}

Answer

By using the button_Click event you are adding the dynamic TextBox to the MainGrid and that code looks fine. But the problem is that this.MainGrid is not in the Present UI, its similar to the dynamically created TextBox, since you ware defined it in the code-behind(see the definition above the constructor Grid MainGrid = new Grid();).

Consider that canContainer is a canvas defined in the xaml as like the following,

<Canvas Height="319" Margin="0"
        Width="517"
        Name="canContainer"/>

To overcome this you can choose any of the following method.

1.Add The MainGrid to the UI. it will add the grid to the canvas, keep in mind the dynamic textBox already added to the Grid. which means the code should be like this -->

 this.canContainer.Children.Add(MainGrid);

2.Add dynamicTextBox to any other parent which is present in the UI.

this.canContainer.Children.Add(dynamicTextBox); 

You you are using this method then need not to define and adding MainGrid