RRFARIA
RRFARIA

Reputation: 53

C# loss of focus on textbox

I already set a standard text and color for the text and when the textbox is clicked I clear the text for the User type text and define color black. on click event:

 if (txtbox.Text == "Ex.: [text test]")
            {
                txtbox.Text = string.Empty;
                txtbox.ForeColor = Color.Black;
            }

I want to set a default text if the textbox is empty and the focus is in another textbox, so if the User clicking or pressing tab.

Upvotes: 0

Views: 280

Answers (4)

spajce
spajce

Reputation: 7082

  private void textBox1_Validating(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(textBox1.Text))
        {
            //Your logic here or the color you want 
        }
    }

Upvotes: 1

MahaSwetha
MahaSwetha

Reputation: 1066

Please, write the below code in both click and keypress event function (for working of tab)

If(txtbox.Text == "")
{
    txtbox.Text = "Default";
    txtbox1.focus();  //focus will be set to another textbox.
}

Upvotes: 0

AkshayP
AkshayP

Reputation: 188

If there are two textboxes txt1 and txt2 on form form1 then

form1_Load(object sender, System.EventArgs e)
{
    txt2.SetFocus;
    txt1.text = "Default Text";
}
txt1_Click(object sender, System.EventArgs e)
{
    if(txt1.text == "Default Text")
    {
        txt1.text = "";
    }
}
txt1_Leave(object sender, System.EventArgs e)
{
   if(txt1.text == "")
   {
        txt1.text = "Default Text";
   }
}

I think it would work.Let me know if any error occurs.

Upvotes: 0

CurtisHx
CurtisHx

Reputation: 758

You could set your default text in the Leave event. This will run any time the text box looses focus.

    private void textBox1_Leave(object sender, EventArgs e)
    {
        if (textBox1.Text == String.Empty)
        {
            //Set default text here.  
        }
    }

Upvotes: 0

Related Questions