问题
I've created an extension class for Textbox as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyApplication.App_Code
{
public class DateTextBox : TextBox
{
protected override void OnPreRender(EventArgs e)
{
//this is what iwant to do :
//((TextBox)sender).Attributes.Add("placeholder", "dd/mm/yyyy");
base.OnPreRender(e);
}
}
}
I need to add a "placeholder" attribute to the textbox control on prerender, but i'm not sure about how to reference the sender textbox control.
回答1:
You just use this
:
this.Attributes.Add("placeholder", "dd/mm/yyyy");
回答2:
The current instance is your textbox. Use this.Attributes
?
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.Attributes.Add("placeholder", "dd/mm/yyyy");
}
回答3:
you don't need sender here. your class instance itself represents the text box.
so simply use :
Attributes.Add("placeholder", "dd/mm/yyyy");
remember, this
automatically considered. so above statement is same as :
this.Attributes.Add("placeholder", "dd/mm/yyyy");
回答4:
An Addition on @kind.code you need to write attributes.add after
protected override void OnPreRender(EventArgs e)
{
// Run the OnPreRender method on the base class.
base.OnPreRender(e);
// Add Attributs on textbox
this.Attributes.Add("placeholder", "dd/mm/yyyy");
}
Another Option
I think you not need to do all this override of Textbox
you can write simple ..as
<asp:TextBox ID="TextBox1" runat="server" placeholder="dd/mm/yyyy" ></asp:TextBox>
来源:https://stackoverflow.com/questions/27731602/how-to-add-an-attribute-to-textbox-in-extension-class