简体   繁体   English

如何在c#codebehind中的动态文本框上设置input type =“number”

[英]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: 我在C#/ ASP.NET网页中有一个动态创建的TextBox,我想要适应移动浏览器:

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> : 我看到我可以直接在纯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? 如何在代码隐藏中使用动态TextBox执行此操作,或者我可以吗?

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? 在渲染后我是否需要使用JavaScript来“破解”控件? (I'd rather have a .NET way of doing it if possible.) (如果可能的话,我宁愿采用.NET的方式。)

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

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: 对于仍然带着同样问题来到这里的人来说,在OP打开这个问题几个月后,微软发布了一个修复问题的更新:

http://support.microsoft.com/kb/2533523 (see issue number 12). http://support.microsoft.com/kb/2533523 (参见第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. 对于Visual Studio 2010,如果您尝试安装它并且它说它不适用于您,请检查您是否有VS2010 SP1。 In that case, simply installing SP1 may solve the problem. 在这种情况下,只需安装SP1即可解决问题。 The download can be found at http://www.microsoft.com/en-us/download/details.aspx?id=23691 . 可以在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.. 在aspx页面注册..

<%@ 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. type属性将取自上面的modifyType属性。 So this can also be currency or any other type with HTML5 supports. 所以这也可以是货币或HTML5支持的任何其他类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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