GridView Templatefield date formatting not working - c#

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.

Related

How to display only date in GridView when pulling data from a DB? C#

I am pulling data from an access database to show in a GridView control on a ASP.NET project. It works fine but I want to see if I can format the data that is being pulled. Currently any currency is being truncated from xx.xx to just the dollar amounts. Also the dates are displaying mm/dd/yyyy hh/mm/ss AM/PM
I tried editing the database itself to the right values (I set the currency field to "Currency" and the date field to "Short Date" but when I pull that date it still shows them not formatted.
EDIT: Sorry, had to take the code down
Any ideas?
Thank you
in the grid view of yours add the property called DataFormatString
DataFormatString examples:
{0:dd MMMM yyyy} - gives 24 February 2006
{0:MMM dd} - gives Feb 24 (substitue MMM with MMMM for the full month name
instead of abbreviation)
{0:dd/MM/yy} - gives 24/02/06
{0:dd/MM/yyyy} - gives 24/02/2006
Sample Code
<asp:BoundField HeaderText="Date"
DataField="SampleDate"
DataFormatString="{0:MM/dd/yyyy}" >
MSDN BoundField.DataFormatString Property
You just need to set the dataformatstring with how you want it to be populated.
As exemplified on the MSDN page:
Money:
<asp:BoundColumn HeaderText="Price" DataField="Price"
DataFormatString="{0:c}" />
With the {0:c}, placing a number after the c value (such as {0:c2}) will give you that many decimal places.
Date:
<asp:boundfield datafield="MyDate" dataformatstring="{0:MM/dd/yyyy}" />
One solution would be:
<asp:GridView ID="gvLEmployees" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name") %>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<%# Convert.ToDateTime(Eval("JoinDate")).ToShortDateString() %>
OR
<%# Convert.ToDateTime(Eval("JoinDate")).ToString("d") %>
</ItemTemplate>
</asp:TemplateField>
</Column>
</Gridview>
You have to Create a BoundField, set its properties including the property dataformatstring which you can use to set format of the field appear in the GridView, and add it to the GridView control.
here below some code
public GridView Cr_GridView(string[] ColNames,string[] ColLable, string[] ColFormat)
{
GridView GV = new GridView();
int x = ColNames.GetUpperBound(0);
for (int i = 0; i < x; i++)
{
BoundField GvField = new BoundField();
GvField.DataField = ColNames[i];
GvField.HeaderText = ColLable[i];
GvField.DataFormatString = ColFormat[i];// for example "{0:dd/MM/yyyy}" for a date field
GV.Columns.Add(GvField);
}
return GV;
}
You can also check if you are using Template Field:
<asp:TemplateField HeaderText="last_modified_date">
<ItemTemplate>
<asp:Label ID="lblModyDate" runat="server" Font-Size="10px" CssClass="ControlStyleUpperCase"
Text='<%# Bind("last_modified_date","{0:dd/MM/yyyy HH:mm:tt}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

'CompareEndTodayValidator' cannot be converted to type 'Date'.?

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;
}
}

System.FormatException: String was not recognized as a valid DateTime

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]));

error handling on page design (source)

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.

Binding time to a textbox

I am using a Masked Editor which is great and simple to use, but I was wondering. Is there a way to bind the time to a textbox that has a masked editor and cause the AM or PM to show up?
I know if you type an A or P AM and PM will show up, but how to you get it to appear to a bound textbox of time?
<asp:TextBox ID="txttime" runat="server" Width="90"></asp:TextBox>
<ajaxToolkit:MaskedEditExtender ID = "MaskedEditExtender1" AcceptAMPM="true" ClearTextOnInvalid="true" ClearMaskOnLostFocus="false" runat="server" TargetControlID="txttime"
Mask="99:99" MaskType="Time"></ajaxToolkit:MaskedEditExtender>
<ajaxToolkit:MaskedEditValidator ID = "MEV" ControlToValidate="txttime" runat="server" ControlExtender="MaskedEditExtender1" IsValidEmpty="false"></ajaxToolkit:MaskedEditValidator>
Here is the code that binds to the textbox. All i see is the time without AM or PM
DateTime datetime = Convert.ToDateTime(DataBinder.Eval(FormView1.DataItem, "Date"));
txttime.Text = String.Format("{0:t}", datetime);
Change
MaskType="Number"
To
MaskType="DateTime"
And include the following parameter:
AcceptAMPM="true"
So it would now be:
<asp:TextBox ID="txttime" runat="server" Width="90"></asp:TextBox>
<ajaxToolkit:MaskedEditExtender ID = "MaskedEditExtender1" AcceptAMPM="true" ClearTextOnInvalid="true" ClearMaskOnLostFocus="false" runat="server" TargetControlID="txttime"
Mask="99:99" MaskType="DateTime" AcceptAMPM="true"></ajaxToolkit:MaskedEditExtender>
<ajaxToolkit:MaskedEditValidator ID = "MEV" ControlToValidate="txttime" runat="server" ControlExtender="MaskedEditExtender1" IsValidEmpty="false"></ajaxToolkit:MaskedEditValidator>
ClearMaskOnLostFocus must be set to true. That was the issue. Thanks for the help.
ClearMaskOnLostFocus="true"
Here's where i found the answer
Click here

Categories