Marina Marina - 7 months ago 56
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()
private void button_Click(object sender, RoutedEventArgs e)
TextBox dynamicTextBox = new TextBox();
dynamicTextBox.Text = "Type Partnumber";
Grid.SetRow(dynamicTextBox, 1);
Grid.SetColumn(dynamicTextBox, 0);


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"

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 -->


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


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