Reputation: 115
I am fairly new to C#. I am trying to add a textbox to the grid by clicking a button. When I click this button, everything on my grid disappears:
private void addLine_Click(object sender, System.EventArgs e)
{
System.Windows.Controls.TextBox txt = new System.Windows.Controls.TextBox();
txt.Name = "textBox8";
dxfLines.Children.Add(txt);
}
Here is the xaml too:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DXFGenerator" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="dxfLines">
<TextBox Height="23" HorizontalAlignment="Left" Margin="271,94,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<Button Content="Generate DXF" Height="23" HorizontalAlignment="Left" Margin="286,194,0,0" Name="button1" VerticalAlignment="Top" Width="84" Click="button1_Click" />
<Button Content="Add Line" Height="23" HorizontalAlignment="Left" Margin="391,196,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="addLine_Click" />
</Grid>
</Window>
Upvotes: 2
Views: 14071
Reputation: 146
If you are using a grid you need to define rows and columns. Your xaml should look something like this:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DXFGenerator" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="dxfLines" x:FieldModifier="private" >
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Grid.Column="2" Grid.Row="4" />
<Button Content="Generate DXF" Height="23" HorizontalAlignment="Left" Grid.Column="1" Grid.Row="6" VerticalAlignment="Top" Width="84" Click="button1_Click" />
<Button Content="Add Line" Height="23" HorizontalAlignment="Left" Grid.Column="2" Grid.Row="6" VerticalAlignment="Top" Width="75" Click="addLine_Click" />
</Grid>
</Window>
You also need to specify a row and column for the text box you are adding so the grid knows where to place the text box. The content of your addLine click should look something like:
System.Windows.Controls.TextBox txt = new System.Windows.Controls.TextBox();
txt.Name = "textBox8";
Grid.SetColumn(txt,1);
Grid.SetRow(txt, 1);
dxfLines.Children.Add(txt);
Besides, keep in mind that, in order to add a new child item, you select the Grid form and not the Window form . The Window form does not have the Children property, however in this example the Grid form has it.
Upvotes: 6