Apply jQuery Date Picker to dynamically added TextBox in ASP.Net

Last Reply 3 months ago By dharmendr

Posted 3 months ago

How to apply Jquery date picker to dynamic textbox control from codebehind.

TextBox txtBox=new TextBox();

 

Posted 3 months ago

Hi amar,

You can provide class attribute to your dynamic TextBox and apply the jQuery DatePicker Plugin.

Check this example. Now please take its reference and correct your code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
    <link rel="Stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
    <script type="text/javascript">
        $(function () {
            $(".datepicker").datepicker({
                showOn: 'button',
                buttonImageOnly: true,
                buttonImage: 'Images/Calendar.png'
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        for (int i = 0; i < 2; i++)
        {
            TextBox txtBox = new TextBox();
            txtBox.ID = "txtDate" + i;
            txtBox.ReadOnly = true;
            txtBox.Attributes.Add("class", "datepicker");
            form1.Controls.Add(txtBox);
            form1.Controls.Add(new Literal() { Text = "<br/>" });
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        For i As Integer = 0 To 1
            Dim txtBox As TextBox = New TextBox()
            txtBox.ID = "txtDate" & i
            txtBox.[ReadOnly] = True
            txtBox.Attributes.Add("class", "datepicker")
            form1.Controls.Add(txtBox)
            form1.Controls.Add(New Literal() With {.Text = "<br/>"})
        Next
    End If
End Sub

Screenshot