views:

228

answers:

3

Hey guys, the following tutorial shows how to take the text from a text box and display it in a text block when the user hits a button. Simple enough... but what I want to do is instead of hitting a button that adds the text I want the enter button to do it.

Searching here, I found the following code but it doesn't seem to do anything.

private void textBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            listBox.Items.Add(textBox.Text);
        }
    }

So, the textbox that has the string is called textbox and I want the text from that textbox to be added to my list (listBox). When I click the enter button, it does nothing. Any help?

Thanks!

A: 

Hi Court,

You'll need to wire this event handler to the textboxes KeyDown event if you haven't done so already. You can do so via the Events tab in the properties window, while the textbox is targeted - or you can double click there and VS will create a new event handler for you which you can put the above code into.

Mick N
Wouldn't the code I have in my post do that? It is hooked into the xaml page as well.
Court
Not by just adding the method. You need to wire the event to the method using one of the techniques I mentioned.
Mick N
A: 

You can intercept the enter key from the on screen keyboard, but not from the keyboard of a PC running the emulator.

Here's some code to prove it works:

Create a new Phone Application. Add the following to the content grid

<ListBox Height="276" HorizontalAlignment="Left" Margin="14,84,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" />

Then in the code behind, add the following:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        this.listBox1.Items.Add(textBox1.Text);
    }
}
Matt Lacey
A: 

@Court from the answer you gave @Trees i can assume you are not really sure if the KeyDown is wired. Do you have the following code in the XAML file?

<TextBox Height="32" HorizontalAlignment="Left" Margin="13,-2,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="433" KeyDown="textBox1_KeyDown" />

@Matt Lacey intercepting Enter from the PC's keyboard also works

undertakeror