如何在动态文本框中删除默认文本

时间:2013-05-28 10:34:48

标签: asp.net focus dynamically-generated

我在asp.net中生成动态文本框并在其上设置默认文本。现在,我想在第一次聚焦时清除文本框,但如果用户没有输入任何内容,请再次显示默认文本。

 protected void btnAdd_Click(object sender, EventArgs e)
{
    TextBox textName;
    textName = new TextBox();
    textName.Text = "mail";
    TextBox textName2;
    textName2 = new TextBox();
    textName2.Text = "tel";
    string divContect = ControlRenderer(divTextBox);
    divTextBox.InnerHtml = divContect + ControlRenderer(textName) + "&nbsp;&nbsp" + ControlRenderer(textName2) + "<br/><br/>";

}

public string ControlRenderer(Control control)
{
    StringWriter writer = new StringWriter();
    control.RenderControl(new HtmlTextWriter(writer));
    return writer.ToString();
}  

2 个答案:

答案 0 :(得分:0)

private void OnTestTextBoxGotFocus(object sender, RoutedEventArgs e)
{  
if (testTextBox.Text.Equals("Type here...", StringComparison.OrdinalIgnoreCase))
    {
        testTextBox.Text = string.Empty;
    }  
}
private void OnTestTextBoxLostFocus(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrEmpty(testTextBox.Text))
    {
        testTextBox.Text = "Type here...";
    }
}

答案 1 :(得分:0)

您可以将Javascript与onblur和onfocus事件一起使用。

希望这会对你有所帮助。

请试试这个:

    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox textName;
        textName = new TextBox();
        textName.ID = "textName";
        textName.Text = "mail";
        textName.ForeColor = System.Drawing.Color.Gray;
        SetPromptText(textName);

        TextBox textName2;
        textName2 = new TextBox();
        textName2.ID = "textName2";
        textName2.Text = "tel";
        textName2.ForeColor = System.Drawing.Color.Gray;
        SetPromptText(textName2);

        string divContect = ControlRenderer(divTextBox);
        divTextBox.InnerHtml = divContect + ControlRenderer(textName) + "&nbsp;&nbsp" + ControlRenderer(textName2);
    }

    public string ControlRenderer(Control control)
    {
        StringWriter writer = new StringWriter();
        control.RenderControl(new HtmlTextWriter(writer));
        return writer.ToString();
    }

    private void SetPromptText(TextBox textBox)
    {
        string onFocusAction = "if (this.value == \"{0}\") {{ this.value = \"\"; this.style.color = \"black\"; }} ";
        string onBlurAction = " if (this.value == \"\") {{ this.value = \"{0}\"; this.style.color = \"gray\"; }} else this.style.color = \"black\";";
        onBlurAction = string.Format(onBlurAction, textBox.Text);
        onFocusAction = string.Format(onFocusAction, textBox.Text);
        textBox.Attributes["onblur"] = onBlurAction;
        textBox.Attributes["onfocus"] = onFocusAction;
    }
相关问题