Reputation: 19
I have this code to show/hide Canvas with some text boxes, and when I press a button it submits data from TextBox1 to database. The problem is that I don't know how to access TextBox1 in C# code behind.
For example this is some of my XAML code:
<ContentControl Background="{x:Null}" >
<ContentControl.Template>
<ControlTemplate>
<StackPanel Grid.Row="3" Height="500" Name="stack1" Width="280">
<Canvas x:Name="canvas1" Height="400" >
<TextBox Height="23" Name="TextBox1" Width="70" />
<Button Content="Submit" Name="submit_button" Click="submit_button_Click" />
</Canvas>
<ToggleButton x:Name="toggleshowhide" Content="Show/Hide" IsChecked="True" Height="50" />
</StackPanel>
<ControlTemplate.Triggers>
<Trigger SourceName="toggleshowhide" Property="IsChecked" Value="True">
<Setter TargetName="canvas1" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger SourceName="toggleshowhide" Property="IsChecked" Value="False">
<Setter TargetName="canvas1" Property="Visibility" Value="Hidden" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
<Button Content="Button" Height="23" Name="submit" Width="74" />
</ContentControl>
And this is what I'm trying to achieve:
private void submit_button_Click(object sender, RoutedEventArgs e)
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO Table VALUES (this.TextBox1.Text), con);
cmd.Connection = con;
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("OK", "Info !");
}
else
{
MessageBox.Show("Some text !", "Error");
}
If anyone can help I`ll really appreciate it. :)
Upvotes: 0
Views: 2207
Reputation: 38385
When accessing elements generated from a ControlTemplate, you need to use the FindName method of the Template. In this case, give your ContnetControl a name:
<ContentControl Background="{x:Null}" x:Name="MyContentControl">
And in the code behind, you can access the value of any of the generated elements by name using the FindName method:
TextBox tb = (TextBox)MyContentControl.Template.FindName( "TextBox1", MyContentControl);
For more information, see: How to: Find ControlTemplate-Generated Elements
Upvotes: 1
Reputation: 12533
give your TextBox an x:Name not a Name ... does that even Compile ?
xaml :
<TextBox x:Name="TextBox1" />
cs :
var s = TextBox1.Text;
Upvotes: 0
Reputation: 12837
string v = this.TextBox1.Text;
OleDbCommand cmd = new OleDbCommand('INSERT INTO Table VALUES (' + v + ');');
BTW this is pretty bad idea, read about sql injection...
Upvotes: 0