How to add an attribute to textbox in extension class

杀马特。学长 韩版系。学妹 提交于 2020-01-15 12:16:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!