Adding textbox & button programmatically -> Button Click event with no content for textbox
I'm pretty new to this and so far I haven't found any solution online which solves my problem.
I'd like to use controls by adding them programmatically, which works and the contents shows in the window, but as soon I want to save the content via button, the event handler doesn't get the variables passed to it.
I've got the following situation where I don't know what I miss. (WPF4, EF, VS2010)
In XAML I have a grid where I'd like to add eg. a textbox and a button from code behind like
<Grid Name="Grid1">
<Grid.RowDefinitions>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="75*"></ColumnDefinition>
<ColumnDefinition Width="25*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox Grid.Row="2" Name="textBox1" />
</Grid >
In code-behind:
private void CheckMatching ()
{
TextBox textBox2 = new TextBox();
textBox2.Text = "textbox to fill";
textBox2.Name = "textBox2";
Grid1.Children.Add(textBox2);
Button SaveButton = new Button();
SaveButton.Name = "Save";
SaveButton.C开发者_StackOverflowontent = "Save";
SaveButton.Click += new RoutedEventHandler(SaveButton_Click);
Grid1.Children.Add(SaveButton);
}
private void SaveButton_Click ( object sender, RoutedEventArgs e )
{
// works fine
string ShowContent1 = textBox1.Text;
// It doesn't show up in intellisense, so I cant use it yet
string ShowContent2 = textBox2.Text;
}
I can access the content of the textbox in XAML or everything else set in XAML, but I don't get the content of anything else I set in code-behind. The content itself is shown in the window.
I tried different approaches already. Nothing worked so far.
This question is not a WPF issue but something very basic to the Object Oriented Computer Programming.
How can you expect that an object (textBox2
) that was delcared and created locally in CheckMatching
method be available in another method like SaveButton_Click
?
For that you can scope it class level.
private TextBox textBox2;
private void CheckMatching ()
{
this.textBox2 = new TextBox();
this.textBox2.Text = "textbox to fill";
this.textBox2.Name = "textBox2";
Grid1.Children.Add(this.textBox2);
.....
}
private void SaveButton_Click ( object sender, RoutedEventArgs e )
{
string ShowContent1 = textBox1.Text; // works fine
string ShowContent2 = this.textBox2.Text; // should work too
}
And then you can also do it WPF way....
private void SaveButton_Click ( object sender, RoutedEventArgs e )
{
string ShowContent1 = textBox1.Text; // works fine
string ShowContent2 = ((TextBox)Grid1.Children[1]).Text; // should work too
}
精彩评论