简体   繁体   English

C#失去对文本框的关注

[英]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. 如果文本框为空并且焦点位于另一个文本框中,那么我想设置默认文本,因此如果用户单击或按下选项卡。

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

You could set your default text in the Leave event. 您可以在Leave事件中设置默认文本。 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.  
        }
    }

Please, write the below code in both click and keypress event function (for working of tab) 请同时在click和keypress事件功能中写入以下代码(用于标签的工作)

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

If there are two textboxes txt1 and txt2 on form form1 then 如果表单form1上有两个文本框txt1和txt2,则

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. 我认为这会起作用。如果发生任何错误,请通知我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM