I am trying to store the selected date of an Ajax Calendar Extender control in a hidden field. I used OnClientDateSelectionChanged to set it.
However, when I select 02/22/2015, the selected date in the script shows as 02/21/2015. I added setting the textbox's value using this selected value, to test it, and it shows as 02/21/2015.
It also sets the value of the hidden field as "Feb 21 19:00:00 EST 2015" which throws an error when trying to convert to datetime.
<asp:TextBox runat="server" ID="tbStartDate" ReadOnly="true" />
<asp:Image runat="server" ID="imgFrom" ImageUrl="Calendar.gif" />
<ajaxToolkit:CalendarExtender runat="server"
ID="calStartDate"
Format="MM/dd/yyyy"
TargetControlID="tbStartDate"
OnClientDateSelectionChanged= "startDateChanged"
PopupButtonID="imgFrom" />
function startDateChanged(sender, args) {
var hfStartDate = document.getElementById('<%=hfStartDate.ClientID %>');
var selectedDate = sender._selectedDate;
hfStartDate.value = selectedDate;
sender._textbox.set_Value(sender._selectedDate.format(sender._format))
}
Related
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.
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>
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 checkbox template field within a gridview in c#, this field also has a hidden field with the id behind it. I want to use jQuery to raise an event on click of the checkbox to grab a datakey value so I can run a query through jQuery and add the checked item to the database. I have seen examples that get datakeys when an overall button is clicked but I want this to happen on each checkbox clicked within the gridview. I currently get "undefined" when trying to access the id.
C# within the gridview
<ItemTemplate>
<asp:CheckBox ID="CheckBox" CssClass="checkbox" runat="server" />
<asp:HiddenField ID="idnum" runat="server" Value='<%# Eval("id") %>' />
</ItemTemplate>
jQuery
$(document).ready(function () {
var gridResults = document.getElementById('<%= grdResults.ClientID %>');
$("form input:checkbox").click(function (e) {
var id = $(this).next('#idnum').val();
alert(id);
return false;
});
});
If there are multiple fields with ID="idnum" you should probably change that to class="idnum". After adding the class you could get the value using:
var gridResults = $(e.target).next('.idnum').val();
If idnum is just an example which is different for each field, you can just use var id = $('#idnum').val();
EDIT: changed e.target.next('.idnum').val(); to $(e.target).next('.idnum').val(); to convert the element to jQuery object
//This is the script to get datakeyname value on check box check event inside GridView
<script type="text/jscript">
$(document).ready(function () {
var gridResults = document.getElementById('<%= grdCateogry.ClientID %>');
$("form input:checkbox").click(function (e) {
var id = $(this).next($('#IDVal')).val();
alert(id);
return false;
});
});
</script>
//This is the GridView
<asp:GridView ID="grdCateogry" DataKeyNames="CategoryId" runat="server">
<Columns>
<asp:TemplateField HeaderText ="Try" ItemStyle-Width="20px">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("CategoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
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