BWilliams
BWilliams

Reputation: 15

Textbox will not accept more than 1 character without disappearing in C#

private void btnClassNameA_Click(object sender, EventArgs e)
    {
        txtbClassNameA.Visible = true;
        txtbClassNameA.Focus();
    }

private void txtbClassNameA_KeyDown_1(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter) ;
        btnClassNameA.Text = txtbClassNameA.Text;
        txtbClassNameA.Visible = false;
    }

Upon clicking of a button, a text box appears. I can't get it to accept more than 1 character at a time without disappearing. It is supposed to disappear by pressing the enter key. Any help would be greatly appreciated!

Upvotes: 1

Views: 649

Answers (4)

Matt N.
Matt N.

Reputation: 197

It appears you have a semicolon after your conditional.

Right now it is evaluating the conditional, and then moving on to update the text and make the box invisible.

private void txtbClassNameA_KeyDown_1(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter) 
        {
            btnClassNameA.Text = txtbClassNameA.Text;
            txtbClassNameA.Visible = false;
        }
    }

Might give you better results.

Upvotes: 0

Seth
Seth

Reputation: 716

Your if statement is not formatted correctly. Try it like this:

if (e.KeyCode == Keys.Enter)
{
        btnClassNameA.Text = txtbClassNameA.Text;
        txtbClassNameA.Visible = false;
}

Upvotes: 1

wblanks
wblanks

Reputation: 598

    private void txtbClassNameA_KeyDown_1(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            btnClassNameA.Text = txtbClassNameA.Text;
            txtbClassNameA.Visible = false;
        }
    }

If that is your actual code, the semicolon might be throwing you off. Try this.

Upvotes: 0

walther
walther

Reputation: 13600

Your current code is equivalent to this:

private void txtbClassNameA_KeyDown_1(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter) { } // does nothing, just evaluates the condition
    btnClassNameA.Text = txtbClassNameA.Text;
    txtbClassNameA.Visible = false;
}

You have to change it like this:

private void txtbClassNameA_KeyDown_1(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
       btnClassNameA.Text = txtbClassNameA.Text;
       txtbClassNameA.Visible = false;
    }
}

Upvotes: 1

Related Questions