Bryan
Bryan

Reputation: 8697

How to automatically detect non-empty textbox?

I'm doing a search function for my webapp.

However, i'm trying to disable my search button if the user does not type any search condition in the search box. Unfortunately, i wasn't able to allow my webapp to automatically detect if the user type something in the search box which will eventually enable the search button. Vice versa, when the user delete any search value from the search textbox the button will be enabled again.

This is how i typed to place the condition in my searchbox called txtData but it doesn't work.

    protected void txtData_TextChanged(object sender, EventArgs e)
    {
        if (!txtData.Text.Equals(""))
        {
            btnSearch.Enabled = true;
        }
    }

Is there any other way to detect words in textbox?

Regards.

Upvotes: 0

Views: 153

Answers (4)

User2012384
User2012384

Reputation: 4919

I suggent you add a validator named requiredfieldvalidator http://www.w3schools.com/aspnet/control_reqfieldvalidator.asp

A requiredfieldvalidator is a validator that checks if the field is empty, if it is, the error message will be shown and won't postback so, in that case, the web app won't do the search function

if you really want to disable / enable the button on client side, I suggest you add a client side event to the textbox called "onblur", and make a function(javascript) that disables the search button if there's no text in the textbox and enable the button if there is.

Or if you really want to use textchanged event on server side, you'll have to set autopostback of that textbox to true

  protected void txtData_TextChanged(object sender, EventArgs e)
    {
            btnSearch.Enabled = (!string.IsNullOrEmpty(txtData.Text.Trim()));
    }

Upvotes: 1

Daniel
Daniel

Reputation: 3374

protected void txtData_TextChanged(object sender, EventArgs e)
{
    if (!txtData.Text.Equals("") || !txtData.Text.toString().Equal(string.empty))
    {
        btnSearch.Enabled = true;
    }
}

Upvotes: 0

David Pilkington
David Pilkington

Reputation: 13620

protected void txtData_TextChanged(object sender, EventArgs e)
{
    btnSearch.Enabled = !String.IsNullOrWhiteSpace(txtData.Text);
}

Upvotes: 2

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

protected void txtData_TextChanged(object sender, EventArgs e)
{
    btnSearch.Enabled = txtData.Text.Length > 0;
}

Upvotes: 0

Related Questions