Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2014-12-25
10
Medium Priority
?
1,157 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 34

Expert Comment

by:Mike Eghtebas
ID: 40518153
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
ID: 40518157
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 34

Expert Comment

by:Mike Eghtebas
ID: 40518160
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
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 

Author Comment

by:lapucca
ID: 40518163
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 34

Accepted Solution

by:
Mike Eghtebas earned 2000 total points
ID: 40518183
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
 

Author Comment

by:lapucca
ID: 40518185
okay, will try it now.  thank you.
0
 

Author Comment

by:lapucca
ID: 40518188
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 34

Expert Comment

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

Author Comment

by:lapucca
ID: 40518194
sounds good, thank you very much!
0
 

Author Closing Comment

by:lapucca
ID: 40527115
Thank you.
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

661 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