Question

I have a web form which several date fields in it, I am using Ajax calender for the user to enter the date, I want to restrict the user from typing in extra info other than the date or even not being able to type anything in the textbox apart the value from the calender extender. I am using ASP.NET, VB.NET and SQL Server 2008 database

My date format is dd-MMM-yy

I tried:

Enable = false 

but it is not saving the date to database

Below is a sample of my code:

<asp:TextBox ID="TextBox5" runat="server" Width="150px" style="margin-top: 0px" 
                            ReadOnly="False" CausesValidation="True"></asp:TextBox>

<asp:CalendarExtender ID="TextBox5_CalendarExtender" runat="server" Format="dd-MMM-yy" PopupButtonID="ImageButton1" TargetControlID="TextBox5">
</asp:CalendarExtender>

Appreciate your help

Thank you

Was it helpful?

Solution

First you'll need to set the textbox as 'read only' in code behind, usually in Page_Load event like this:

TxtDate.Attributes.Add("readonly","readonly");

Next, modify the design of the textbox to be like this in markup:

   <asp:TextBox ID="TxtDate" runat="server" Width="150px"></asp:TextBox>

    <a href="JavaScript:clearText('<%=TxtDate.ClientID %>')">
    <img alt="" src="../clear.png"></img></a>
    <asp:CalendarExtender ID="CalendarExtender1" runat="server" Enabled="True" 
    Format="dd-MMM-yy" PopupPosition="Right" TargetControlID="TxtDate">      
</asp:CalendarExtender>

And finally add this small script to clear the date:

   <script type="text/javascript">
        function clearText(ctrl) {
            document.getElementById(ctrl).value = "";
        };

By doing this, you will have a textbox when clicking on it it will pop up the calendar, it will not allow users to type in, and when the user click on the "clear" image associated with the textbox, it will clear the text.

OTHER TIPS

Don't set ReadOnly = True or Enabled = False that will prevent the value from being posted back. You need to only prevent user interaction while allowing value to be updateable otherwise. One way is to prevent field from obtaining focus, try adding this attribute:

onfocus = "this.blur();"

For more take a look at this post.

Setting Readonly attribute will not cause server side process . we can use contentEditable="false" it will be available on server side

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top