2013-05-28 61 views
1

我在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(); 
} 

回答

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..."; 
    } 
} 
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; 
    } 
+0

感謝,它的作品時,我改變所有{0} .value的對THIS.VALUE。 – NASRIN

+0

另一個問題:我設置了輸入灰色的默認顏色,當用戶輸入郵件和電話時,輸入的顏色變爲黑色,但顏色不變黑。我在Button1_Click方法中添加此代碼: textName.ForeColor = System.Drawing.Color.Gray; 並在onFocusAction中添加此代碼: this.style.color = \「#000 \」;但這不起作用。 – NASRIN

+0

好的, 我已經將SetPromptText更改爲以灰色顯示默認文本,並在用戶輸入文本時將forecolor變爲黑色。 希望這會幫助你! – agarici