I am using AJAX calender extender with a textbox, And i want to disable past dates, so that user do not able to select those, which are less than today's date. My code is as follows
In .aspx page
<asp:TextBox ID="txtFromDate" runat="server" ontextchanged="txtFromDate_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtFromDate">
</asp:CalendarExtender>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
and on .cs page
protected void txtFromDate_TextChanged(object sender, EventArgs e)
{
DateTime dt1 = DateTime.Parse(txtFromDate.Text);
if (dt1 < DateTime.Now)
{
//Response.Write("you can not choose date earlier than today's date");
txtFromDate.Text = null;
}
}
But i am getting the following error:
System.FormatException: String was not recognized as a valid DateTime.
and is there any way that i can make those date unclickable so that user cant choose from them using startDate and Enddate attributes, or by some other means, I also tried those but again i got error that these are not supported. Any help will be appreciated.
Try this if your Date's format is "yyyy/MM/dd":
String[] date = typedDate.Text.Split(new char[] { '/' });
Datetime dy = new DateTime(int.Parse(date[0]), int.Parse(date[1]), int.Parse(date[2]));
Related
I am a noob at ASP, I am trying to take take a selected date from an ASP calendar and save that in a textbox or something that I can compare with the second selected date so that the second is larger. I'm not sure if it is possible while just using one calendar. I tried but do not know how to save the first date collection for comparison. I tried both ways but failed miserable. I did do a search but they are using javascript, or java and other languages I do not know.
What I want to do:
I am trying to take two separate inputted dates from user. when 1st date is inputted, store in something, then validate that the user selects a date after the 1st selected date. If not return error message
<asp:TextBox ID="response" runat="server" />
<asp:TextBox ID="caldate1" runat="server" />
<asp:TextBox ID="caldate2" runat="server" />
<asp:CompareValidator ID="calvalidae" runat="server" ControlToCompare="caldate1" ErrorMessage="Date should be later than first date" Type="Date" operator="GreaterThan" ValueToCompare="caldate2"></asp:CompareValidator>
<asp:Calendar ID="cal1" runat="server"></asp:Calendar>
<asp:Calendar ID="cal2" runat="server" SelectionMode="Day" OnSelectionChanged="cal1_SelectionChanged" ></asp:Calendar>
//serverside
protected void cal1_SelectionChanged(object sender, EventArgs e)
{
caldate1.Text = cal1.SelectedDate.ToShortDateString();
if (cal1.SelectedDate.Date > cal2.SelectedDate.Date)
{
caldate1.Text = "You selected ";
caldate1.Text += cal1.SelectedDate.ToShortDateString();
}
else
{
caldate1.Text = "Select a valid date";
}
}
If you just want to compare the dates in code behind do the below
Markup
<asp:CompareValidator ID="calvalidae" runat="server"
ControlToValidate ="caldate1" ValueToCompare="text" ControlToCompare="caldate2"
ErrorMessage="Date should be later than first date" Type="Date"
operator="GreaterThan" ></asp:CompareValidator><br/>
<asp:Calendar ID="cal1" runat="server" OnSelectionChanged="cal1_SelectionChanged1"></asp:Calendar><br/>
<asp:Calendar ID="cal2" runat="server" SelectionMode="Day" OnSelectionChanged="cal2_SelectionChanged" ></asp:Calendar><br/>
</div>
Code Behind
protected void cal1_SelectionChanged1(object sender, EventArgs e)
{
caldate1.Text = cal1.SelectedDate.ToShortDateString();
IsValidDate();
}
protected void cal2_SelectionChanged(object sender, EventArgs e)
{
caldate2.Text = cal2.SelectedDate.ToShortDateString();
IsValidDate();
}
private void IsValidDate()
{
response.Text = string.Empty;
if (cal1.SelectedDate > cal2.SelectedDate)
{
response.Text = "Date should be later than first date";
}
}
Code on aspx:
<EditItemTemplate>
<asp:TextBox ID="TextBox12" runat="server" Text='<%# Bind("Release_Dt", "{0:yyyy-MM-dd}") %>'></asp:TextBox>
<asp:CustomValidator runat="server" ID="Release_Dt_vdt1"
ControlToValidate="TextBox12" onservervalidate="validate_dt"
ErrorMessage="enter valid date" ValidationGroup="UpdateVdtGrp" ForeColor="Red" Display="Dynamic" SetFocusOnError="true">
</asp:CustomValidator>
</EditItemTemplate>
Validation code (in code behind):
protected void validate_dt(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
Question: The date format keeps changing from "yyyy-MM-dd" to short / long date format as shown below every time the row is updated (even just clicking "edit" and "update" on the default gridview buttons without changing any content / dedicated editing 'textbox12'). What is the cause, and how could we fix it?
I have clarify that the SQL database connected to, which this data is stored as string, does not auto-format the data when updated.
If I am missing some piece of important info for the question please advise, thanks in advance.
This is the code i am using in my aspx page
<asp:TextBox ID="ReqFromTxtBox" runat="server" class="textBox" Width="155px" onKeyPress="javascript: return false;" onPaste="javascript: return false;">
</asp:TextBox>
<cc1:CalendarExtender ID="ReqFromTxtBox_CalendarExtender" runat="server" PopupButtonID="ReqFromCalendarBtn" TargetControlID="ReqFromTxtBox">
</cc1:CalendarExtender>
For diabling Future Dates on pageload event set EndDate to Today Date using DateTime.Now:
protected void Page_Load(object sender, EventArgs e)
{
ReqFromTxtBox_CalendarExtender.EndDate = DateTime.Now; //to disable future Dates
}
and for Disabling past dates you have to set StartDate to Today :
protected void Page_Load(object sender, EventArgs e)
{
ReqFromTxtBox_CalendarExtender.StartDate= DateTime.Now; //to disable past Dates
}
Reference Link How To Disable Past of Future Date of Calendar Extender
I have a calender control ,when selecting a date it should be displayed on an associated text box in "dd-mm-yyyy" format . And have a compare validator which should validate the selected date ,if it is greater than today's date. I have written like this
<asp:TextBox runat="server" ID="tb_date" BackColor="White" ></asp:TextBox>
<asp:Calendar ID="EndDate" runat="server"
OnSelectionChanged="EndDate_OnSelectionChanged"
</asp:Calendar>
<asp:CompareValidator runat="server" ID="CompareEndTodayValidator" ErrorMessage="Exam date can't be less than today"
ControlToValidate="tb_date" Type="Date" Operator="LessThanEqual" > </asp:CompareValidator>
protected void Page_Load(object sender, EventArgs e)
{
CompareEndTodayValidator.ValueToCompare = DateTime.Now.ToString("dd-MM-yyyy");
}
protected void EndDate_OnSelectionChanged(object sender, EventArgs e) //COMPARE VALIDATOR FOR EXAM DATE
{
tb_date.Text = EndDate.SelectedDate.ToString("dd-MM-yyyy");
}
It Shows an error
The value '26-09-2013' of the ValueToCompare property of
'CompareEndTodayValidator' cannot be converted to type 'Date'.
Please help. I have tried it with by changing type="string". but failed.When putting mm-dd-yyyy frmat it works properly .But I need in dd-mm-yyyy format
The problem is that the date format that you are converting your selected calendar value to is NOT compatible with the default DateTime.Parse, which is what the Comparer validator no doubt uses internally. Use a different date format or else use the CustomValidator control so you can control the date parse format manually.
DateTime date = DateTime.Parse("26-09-2013"); // Fails
I hope this helps.
EDIT - Using Custom Validator
<asp:CustomValidator runat="server" ID="CompareEndTodayValidatorCust" OnServerValidate="ServerValidation" ControlToValidate="tb_date" ValidateEmptyText="True" ErrorMessage="Exam date can't be less than today" />
protected void ServerValidation (object source, ServerValidateEventArgs arguments)
{
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "dd-MM-yyyy";
DateTime dtToValidate = DateTime.ParseExact(tb_date.Text, format, provider);
arguments.IsValid = (dtToValidate <= DateTime.Now.AddDays(-1));
}
P.S.
Also in the form submit handler or page load method you'll want to check that Page.IsValid == true before allowing the save operation to proceed.
P.S.S
If you want to get more fancy you could provide a JavaScript method in the ClientValidationFunction property and validate client side too. That may be overkill though.
Try with CustomValidator like following
ASPX
<asp:TextBox runat="server" ID="tb_date" BackColor="White" ></asp:TextBox>
<asp:Calendar ID="EndDate" runat="server"
OnSelectionChanged="EndDate_OnSelectionChanged" ></asp:Calendar>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid date">
</asp:CustomValidator><br />
Code behind:
protected void EndDate_OnSelectionChanged(object sender, EventArgs e) //COMPARE VALIDATOR FOR EXAM DATE
{
CustomValidator1.IsValid = true;
DateTime SelectedDate = EndDate.SelectedDate.Date;
DateTime NowDate = DateTime.Now;
tb_date.Text = SelectedDate.ToShortDateString();
if (SelectedDate.Date > NowDate.Date)
{
CustomValidator1.IsValid = false;
}
}
I have a control in GridView which converts dateformat From MMddyyyy To ddMMyyyy.
<ItemTemplate>
<asp:Label ID="lblName" runat="server"
Text='<%# Eval("Value1") != DBNull.Value ?
(Convert.ToDateTime(Eval("Value1")).ToString("dd/MM/yyyy")) : Eval("Value1") %>'>
</asp:Label>
</ItemTemplate>
This works perfectly if it gets a date or null value.
But in my case Value1 (the Bind Field) can be a string containing anything. say - 'garbageStr'.
So it fails to convert to date and throws error.
Instead I want to display null or blank value when it fails to convert to DateTime format.
Is there any way to handle this?
you can define a method for this purpose in code behind , and call it, then in method implementation try conversion in DateTime.TryParse and return string accrdingly
In your aspx file:
<asp:Label ID="lblName" runat="server" Text='<%# ReturnPropertDateTime(Eval("Value1")) %>'> </asp:Label>
In your Code Behind file:
protected DateTime ReturnPropertDateTime(object val)
{
DateTime dt = null;
string dateTimeValue = Convert.ToString(val);
DateTime dateTime2;
if (DateTime.TryParse(dateTimeValue.ToString("ddMMyyyy"), out dateTime2))
{
dt = dateTime2;
}
else
{
dt = // Just Assign Default date time value you want.
}
return dt;
}
Although its tedious, but you can make your aspx file more readable through this approach as it prevents clutering and provide flexible handling.