Solved

How to display only Date part of a datetime data that is bind to a gridview control?

Posted on 2014-12-25
10
695 Views
Last Modified: 2015-01-01
Hi, I'm using vs2012.
I have to convert one of the gridview column to a templatefield instead of a bounfield because i need to add validation control to it.  The regular expression validator is to make sure users enter correct date format during Editing mode.  However, I lost the DataFormat in the property.  I only want to display the date part.  The regular expression I have configure also only validates Date.  I also limit the max characters to be 10 in the Textbox.  However, the data bind to the column is datetime type and upon page load, it displays date and time, mm/dd/yyyy hh:mm:ss
Is there a way to fix this?  Thank you.
0
Comment
Question by:lapucca
  • 6
  • 4
10 Comments
 
LVL 33

Expert Comment

by:Mike Eghtebas
Comment Utility
try:
// code behind
private object FormatDate(DateTime input)
{
    return String.Format("{0:MM/dd/yy}", input);
}

// html
<asp:TemplateField HeaderText="DateFieldCaption">
        <ItemTemplate>
            <asp:Label ID="Label8" runat="server" 
                Text='<%# FormatDate(Eval("DateFieldName")) %>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>

Open in new window

0
 

Author Comment

by:lapucca
Comment Utility
Data bind is of DateTime? type so I just changed that in the FormatDate's parameter.

in my code, do I put "FormatDate(Eval("inside of "Bind"?  Like below?  Or would it work with Bind?  Thank you.

            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("DataFieldName") %>'></asp:Label>
            </ItemTemplate>
0
 
LVL 33

Expert Comment

by:Mike Eghtebas
Comment Utility
try a simpler solution if you prefer not to have code behind. I was about to change it but you beat me to it:

Text='<%# Eval("DataFieldName","{0:d}") %>'

re:>  would it work with Bind?
In these situation you are in advantage because you have the code to try it
0
 

Author Comment

by:lapucca
Comment Utility
I like the Eval solution better.  However, it works when the grid is load up.  However, when I click on the Edit, in the edit mode the textbox is displayed with year and time.  

Either I have to find a regular expression that would validate both date and time or is there a easy way to have a calendar/date time picker control for this column of template field?  T

The data is datetime? type.  At minimum, user need to be able to edit the date if it's too complicate for them to edit time then that's fine.  But I need to make sure if no date time picker pop up then at lease a date/time regular expression is in the validator control working properly.  What would you suggest to do that would be the easiest way for this?
Thank you.
0
 
LVL 33

Accepted Solution

by:
Mike Eghtebas earned 500 total points
Comment Utility
I found the following at: http://forums.asp.net/t/1248131.aspx
FYI 
To create a pop up calendar in a Gridview that populates a textbox with a date do the following: 
1. Create a aspx page and place a gridview control on it and set the autoGenerateColumns to false and the autoGenerateEditButton to true 

2. Drag a SQL or Access Datasource on to the page 

3. Configure the datasource and then set the Gridviews DatasourceID to the newly create datasource 

4. Create an ItemTemplate, in the Gridview for, the column you want to have a pop up calendar appear in. 

5. Then create an EditItemTemplate and put the following tags inside: 
<input name="txtboxname" type="text" value='<%# Eval("nameofcolumn")%>' -- An HTML textbox is required for this to work.  I used a <%#Eval%> to place the current date in the textbox when the user clicks on the edit link. 

<a href="javascript:;" onclick="calendar('<%#Eval("nameofcolumn"%>', 'txtboxname')">Calendar</a> 
If you want to add an image just place that tag in between the <a> tag. <a><img></a> 

6. Next, we must create the javascript function.  Go to the <head> section of your aspx page and type the following: 

<script language="javascript" type="text/javascript"> 
function calendar(strField, formname) 
{ 
window.open('calendar.aspx?formname=form1.' + formname + '&startdate=' + strField, 'calendarpopup', 'width=give a number, height=give a number'); 
} 
</script> 

The formname will be used on the calendar.aspx page to know what textbox to send the selected date back to and the strField will be used to set the current date on the calendar. 

7. Next we will create the calendar.aspx page.  Place a calendar control onto the page.  In the <head> tag type the following: 

<asp:label id="lblMsg" runat="server"></asp:label> 

8. In the code behind add the following if page is not posted back: 

Protected Sub Page_Load(ByVal sender as Object, ByVal e as System.EventArgs) Handles Me.Load 

If not page.ispostback then 
Dim startDate as string = Request.Querystring("startDate") 
Calendar1.todaysDate = startdate 
End If 

End Sub 

This sets the current date to the date in the textbox from the gridview. 

9. Now we will create a selectionChanged method for the calendar. 

Protected Sub Calendar1_SelectionChanged(ByVal sender as Object, ByVal e as System.EventArgs) Handles Calendar1.SelectionChanged 

Dim StrAction as String = "<script language=""javascript"">" 
strAction &= "window.opener." & _ 
HttpContext.Current.Request.QueryString("formname") & ".value= '" & _ 
calendar1.SelectedDate & "'; window.close();" 
strAction &= "</script" & ">" 

lblMsg.Text = strAction 
End Sub 

Do not deveate from this code until you know how it works. 

10. And thats it.  Run it and select a date.  The calendar window will close after date selection and the date will populate back into the textbox on the gridview page

Open in new window


I am trying to reproduce it to make sure it works. You are welcome to try it yourself as well.
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:lapucca
Comment Utility
okay, will try it now.  thank you.
0
 

Author Comment

by:lapucca
Comment Utility
Having a bit hard time following the url you provided.  I think it's time for my brain to reboot.  It's passed 11pm here.  

I asked for help with calendar earlier but I can't get it to work in my code.  I got a jQuery code here, http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_28584726.html

I put the jQuery reference in the Site master file's header.  I then put the block of script at the end of the page content tag. However, no pop up calendar when I click on the grid in the edit mode.  it's just a text box for editing as usual.  I don't know if it's because I didn't put the corrent ClientID in the code but never really got answer to that.

<script type="text/javascript">
    jQuery(function ($) {
        $("#<%= myGrid.ClientID %>").on("click", "tr td:last-child text:last", function () {
            $(this).datepicker();
            $(this).datepicker("show");
        });
    });
</script>
</asp:Content>
0
 
LVL 33

Expert Comment

by:Mike Eghtebas
Comment Utility
I am in PST too. Next I will work at it will be in the morning.
0
 

Author Comment

by:lapucca
Comment Utility
sounds good, thank you very much!
0
 

Author Closing Comment

by:lapucca
Comment Utility
Thank you.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now