简体   繁体   中英

How to set input type=“number” on dynamic textbox in c# codebehind

I have a dynamically created TextBox in a C#/ASP.NET web page that I want to adapt to mobile browsers:

TextBox qtybox = new TextBox();  
qtybox.ID="qtybox";   
qtybox.Text = "0";  
qtybox.Width = 30;   
container.Controls.Add(qtybox);

I see that I can directly set this in a plain HTML <form> :

<input type="number">

...which will then bring up the numeric keyboard.

How can I do this with my dynamic TextBox in the codebehind, or can I?

Is there an alternate way to put a numeric input control on my page dynamically from the codebehind that would work better? Do I need to use JavaScript to "hack" the control after it renders? (I'd rather have a .NET way of doing it if possible.)

我是从记忆中写的,但我认为是:

qtybox.Attributes.Add("type", "number");

For anyone still coming here with the same problem, a few months after the OP opened this question Microsoft released an update that fixes the problem:

http://support.microsoft.com/kb/2533523 (see issue number 12).

For Visual Studio 2010, if you try to install it and it says it doesn't apply to you, check that you have VS2010 SP1. In that case, simply installing SP1 may solve the problem. The download can be found at http://www.microsoft.com/en-us/download/details.aspx?id=23691 .

This can be done using a custom control. Here you go...

namespace CustomTextBoxControls
{
    public class TextBoxWithType : TextBox
    {
        public string modifyType { get; set; }

        protected override void Render(System.Web.UI.HtmlTextWriter output)
        {
            if (!string.IsNullOrEmpty(modifyType))
            {
                output.AddAttribute("type", modifyType);
            }

            base.Render(output);
        }
    }
}

Register it in aspx page..

<%@ Register Namespace="CustomTextBoxControls" TagPrefix="CustomControl" Assembly="CustomTextBoxControls" %>

<CustomControl:MaskedTextBoxWithType id="txtNumber" modifyType="number" runat="server"></CustomControl:MaskedTextBoxWithType>

The type attribute will be taken from the modifyType property above. So this can also be currency or any other type with HTML5 supports.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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