convert an sql datetime column to .net datetime data type in front end...?

I have a field (ldate) in a table that typically displays data in the following format:

2007-11-12 20:30:47.000

In the front end I want the time and the date separately. But as I try to cast it to a datetime object it is giving me a System.NullReferenceException. What I tried to do was just this:

 

Protected Sub gvTopics_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvTopics.RowDataBound
        Dim img As Image = gvTopics.FindControl("imgIcon")
        Dim lbDate, lbTime As Label

        lbDate = gvTopics.FindControl("lbDate")
        lbTime = gvTopics.FindControl("lbTime")

        Dim dt As New DateTime

        If e.Row.RowType = DataControlRowType.DataRow Then
            Debug.Print("parsed = {0}", DateTime.Parse(e.Row.DataItem("ldate")).ToShortTimeString) 'this works!!!
            dt = DateTime.Parse(e.Row.DataItem("ldate"))
            lbDate.Text = dt.ToShortDateString 'throws error at this line
            lbTime.Text = dt.ToShortTimeString
        End If        

End Sub

  

Is there a solution where in I can extract the time and date from inside this event procedure itself? 

 


programming blog
0
deostroll
11/13/2007 2:33:43 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

8 Replies
1795 Views

Similar Articles

[PageSpeed] 48

My guess is that gvTopics.FindControl("lbDate") is not able to find that control. And, hence lbDate is never referenced an object. As a result, when you are trying to access lbDate.Text, it is giving NullReferenceException.

 - Surya

0
dtnetDeveloper
11/13/2007 3:51:38 AM

deostroll:
In the front end I want the time and the date separately

use this sqlquery to retrieve only time

SELECT 
    CONVERT(CHAR(12), DateColumn, 114) 
FROM 
    table 
[WHERE ... ]

use this query to retrieve only date

SELECT CONVERT(VARCHAR(10),GETDATE(),111)

store the result of this query in a ctrl and dispaly it 

in your code, set a breakpoint where you are getting error and trace out the error to find out whether the lbdate.text got any values or not


Mark as Answer if any posts helps you

To Make your dreams come true, Don't Sleep

Remember that no person is an island. Communicate your thoughts and desires honestly, and encourage others to communicate honestly with you. Practice understanding and motivating other people.

Cheers,
RR
0
Mc
11/13/2007 4:29:38 AM

dtnetDeveloper:  seems you are correct. The markup for my gridview is as follows.

  

1    <asp:GridView ID="gvTopics" runat="server" AutoGenerateColumns="False" CssClass="gvclass">
2 <Columns>
3 <asp:TemplateField>
4 <ItemTemplate>
5 <asp:Image ID="imgIcon" runat="server" />
6 </ItemTemplate>
7 </asp:TemplateField>
8 <asp:TemplateField HeaderText="subject">
9 <ItemTemplate>
10 <asp:HyperLink Font-Names="Verdana, Helvetica, Arail" Font-Size="8pt" ID="hlnkPost" 11 runat="server">HyperLink</asp:HyperLink><br />
12 <asp:Label ID="lbStatDate" Font-Size="7pt" runat="server" Text="Label"></asp:Label>
13 </ItemTemplate>
14 </asp:TemplateField>
15 <asp:BoundField DataField="sby" HeaderText="author" />
16 <asp:BoundField DataField="PostsCount" HeaderText="posts" />
17 <asp:TemplateField HeaderText="last update">
18 <ItemTemplate>
19 <asp:Label ID="lblDate" runat="server" Text="Label"></asp:Label>
20 <br />
21 <asp:Label ID="lblTime" runat="server" Text="Label"></asp:Label>
22 </ItemTemplate>
23 </asp:TemplateField>
24 </Columns>
25 </asp:GridView>
 

Can you tell me how to access the controls inside of them... I have not had that much luck.

 

 


programming blog
0
deostroll
11/13/2007 3:29:07 PM

 RowDataBound is the wrong event to do the FindControl in.   Why?  Because the controls have not been rendered yet. 

 

Are you using a Codebehind DataSet or Source?  If so, try using the ItemCreated event instead.

 

Are you using a <asp:SqlDataSource>??  If so, it's really simple in that you can use the same datacolumn twice like your code behind as follows:

<asp:Label runat="server" ID="lbDate" Text='<%# DataBinder.Eval(Container.DataItem, "Date", "{0:d}")%>' />

<asp:Label runat="server" ID="lbTime" Text='<%# DataBinder.Eval(Container.DataItem, "Date", "{0:t}")%>' /> 


If this post helped you, Mark As Answer.
0
jpuckett
11/13/2007 3:40:30 PM

deostroll:
Can you tell me how to access the controls inside of them...

 

For Each row As GridViewRow In gvtopics.Rows

Dim mylbldate As label = DirectCast(row.FindControl("lbldate"), label)

dim mylbltime as label =DirectCast(row.FindControl("lbltime"), label)

End If


Mark as Answer if any posts helps you

To Make your dreams come true, Don't Sleep

Remember that no person is an island. Communicate your thoughts and desires honestly, and encourage others to communicate honestly with you. Practice understanding and motivating other people.

Cheers,
RR
0
Mc
11/13/2007 11:41:43 PM

Hi deostroll,

If you use gvTopics.FindControl("lbDate") in RowDataBound method , you will always get null reference. You can use e.Row.FindControl("controlid") instead.

See my sample,

 

1    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 
2        If Not IsPostBack Then 
3            Dim table As New DataTable() 
4            table.Columns.Add("time") 
5            Dim dr As DataRow = table.NewRow() 
6            dr("time") = "7-11-12" 
7            table.Rows.Add(dr) 
8            Me.GridView1.DataSource = table 
9            GridView1.DataBind() 
10       End If 
11       
12       
13   End Sub 
14   
15   Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) 
16       
17       
18       If e.Row.RowType = DataControlRowType.DataRow Then 
19           Dim test As Label = DirectCast(Me.GridView1.FindControl("lbDate"), Label) 
20           'null 
21           Dim lbl As Label = DirectCast(e.Row.FindControl("lbDate"), Label) 
22           
23           lbl.Text = DirectCast(e.Row.DataItem, DataRowView)("time").ToString() 
24       End If 
25   End Sub
 

 


 

 

1    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="343px" OnRowDataBound="GridView1_RowDataBound">
2                <Columns>
3                    <asp:TemplateField>
4                        <ItemTemplate>
5                            <asp:Label ID="lbDate" runat="server" Text="Label"></asp:Label>
6                        </ItemTemplate>
7                    </asp:TemplateField>
8                </Columns>
9    </asp:GridView>
 

Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
11/15/2007 9:22:00 AM

There is another less intuitive way.  It goes like this:

dim lbl as Label = e.Row.Cells(0).Controls(0)

 The only problem is the index of Controls(). I had to find the exact index through debugging, and checking what was the type of each control in each cell.
 


programming blog
0
deostroll
11/15/2007 2:42:44 PM

deostroll:

There is another less intuitive way.  It goes like this:

dim lbl as Label = e.Row.Cells(0).Controls(0)

 The only problem is the index with Controls(). I had to find the exact index through debugging, and checking what was the type of each control in each cell.
 

I would avoid this approach like the plague!  It is very prone to breaking.  If a new column gets added to the display (with a lower index number), all your control logic becomes invalidated.  It's nasty to fix.

0
david
11/15/2007 2:49:42 PM
Reply:

Similar Artilces:

Convert .NET DateTime format to SQL DateTime format
Hi!!I'd like to know if there is a function to convert the DateTime format used in C# (VS2005) : dd/mm/yyyy HH:mm:ss to the format used in SQL Databases: yyyymmdd HH:mm:ssThanks folks!...

Trying to convert column from datatype nvarchar to datetime
Hi All,  I am trying to simply change a column from a datatype of nvarchar to a datetime datatype.  However when I do I receive the following error message: " Arithmetic overflow error converting expression to data type datetime."To note there is already a date filled out in the columns which I presume the reason why the error is reporting?! however for some reason when originally setup datetime was not used but rather nvarchar to capture the data.The format is: 16/01/2007 09:53:50 There are around 24000 entries that I need converting somehow so if anyone can help...

Issue when converting XML dateTime to .NET DateTime
Hi, I am experiencing an issue when deserializing XML dateTime nodes in ASP.NET in some timezones. The construct 0001-01-01T00:00:00.0000000+ZZ:ZZ where ZZ:ZZ is the timezone offset for the timezone on the current system should produce a DateTime value equalling the constant DateTime.MinValue when converted. This works some of the time, such as for the Paris time offset of +1: (CDate("0001-01-01T00:00:00.0000000+01:00") = DateTime.MinValue) = True But does not work for Sydney time offset of +10: (CDate("0001-01-01T00:00:00.0000000+10:00") = DateTime....

.NET DateTime and SQL Server DateTime problem
.NET DateTime and SQL Server DateTime problem  I have the following if statement in an SQL stored procedure: IF (@Image = 1 AND @DateTimeUploaded = (SELECT ImageMainDateTime FROM Images WHERE UserID = @UserID))   The value of the @DateTimeUpdated variable was taken from the ImageMainDateTime field when the data was requested by a ASP.NET webpage and is passed back here when that page is submitted so I can compare what the DateTime was when the data was requested with what it is now, in other words I’m doing a concurrency check (I can’t use TimeStamp for many reasons, ...

How to convert varchar data type into datetime data type without data lose
Hi all, i have stored date as varchar(30) data type and Date format is dd/MM/yyyy now i have to convert it into datatime data type can u help me in query ?  i have 330 records and each recod contain the Date in format of dd/MM/YYYY but due to varchar data type i can not perform calculation on Date so i have to convert into datetime without data lose. please help me in this regard. Best RegardsRameezWaheed  life is name of learning!Mark as an answer if it helps You can check these posts http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2039108&SiteID=17   ...

System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
After clicking my update button I'm receiving this error:    The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been...

System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
After testing out the application i write on the local pc. I deploy it to the webserver to test it out. I get this error. System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. Notes: all pages that have this error either has a repeater or datagrid which load data when page loading. At first I thought the problem is with the date, but then I can see that some other pages that has datagrid ( that has a date field) work just fine. anyone having this problem before?? hopefully you guys can help...

c# datetime type into sql datetime type
hi, i'm trying something that should be very simple...trying to insert a datetime type from a web form into sql datetime columnthe code:commandSql.Parameters.AddWithValue("@dteDOB", this.DOB); //DOB is datetime typethe sql column is dteDOB (sql datetime type)the error i get: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.do i need to convert it to a string when using parameters with value ? what am i missing here ?thanks,Sharon. The problem is usually that the .NET DateTime object does not have the same range as the SQL one. So if you h...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
 Hello,When i run my project in VS IDE i dont get this below mentioned error but assoon as i put it in IIS of my server machine i get this error.I am using this application since months and wasn't getting any error. But recently when my admin made some changes in server..This error started coming. I have no help from my admin regarding this.  Let me know if i have to do some changes in c# code or in database or in windows server machine or in IIS or in crystal report properties !! The error is as follows : Normal 0 false false false ...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Normal 0 false false false MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-b...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Hello this is my code: ( I want to see if the date is in a month of a selected year)Dim command As New SqlCommand command.Connection = connection command.CommandType = CommandType.Text command.CommandText = "SELECT count(*) fROM tblRequests r WHERE r.StateID =4 AND r.CategoryID <>2 AND r.CompletionDate BETWEEN '" & year & "-" & teller & "-01' AND '" & year& "-" & teller + 1 & "-01'"Dim objaantal As Object = command.ExecuteScalar() Dim Incidents As Integer If Not objaantal Is No...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
I still don't know what is happening with my application. I used before in another page the formview control and I didn't have the out of range Date error. It was normally. But now, I'm doing everything manually and I don't know why, but I'm with this problem. I need to safe this problem today... Here go my code!Thanks Raphael <%@ Page Language="VB" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SQLClient" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> ...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
  Hi , i m inserting the values in the fallowing ways INSERT INTO LoginHistory([UserID],[LoginTime],[LoginIP])VALUES('NilCom1Ad01','13-04-2009 4:52:54 PM','127.0.0.1' ) Still i  m Geting errror  The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.The statement has been terminated.Plz  help me  I'm wondering if your database is expecting month/day/year, in which case 13 would be causing your problem.  Change the date to 04-13-2009 and give it a try.C# <---> V...

conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
  When I run this error I get this error  ' The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.' select distinct pro.prodname, pro.price, pro.description, pro.fromdate, pro.todate, pro.pic1 from products pro inner join booking on pro.category=booking.category where pro.category=1 and '12/11/2008' between pro.fromdate and pro.todate and '18/12/2008' between pro.fromdate and pro.todate and '12/11/2008' not between booking.checkin and booking.checkout and '18/12/2008' not between booking.chec...

Web resources about - convert an sql datetime column to .net datetime data type in front end...? - asp.net.presentation-controls

Is there a JQuery plugin to convert UTC datetimes to local user timezone?
If I have a tag: &lt;span class="utctime"&gt;2010-01-01 11:30 PM&lt;/span&gt; I would like a jquery script or plug in to convert every utctime ...


Targetprocess 3.7.3: Epic unit for Bug/Story cards, new DateTime functions in Webhook plugin
Webhook plugin supports new DateTime functions AddDays(DateTime date, int days) – Returns a new date with the number of days added. The number ...

Common Pitfalls when working with DateTime’s
In .NET, the DateTime structure provides us wonderful functionality, but this seemingly simple structure can cause a lot of headaches if you ...

Parsing Twitter Date format to .Net DateTime
Recently when I needed to parse the twitter datetime format into a .Net DateTime I found this post on the web showing how to do it. However, ...

C Sharp (programming language) - Wikipedia, the free encyclopedia
(pronounced see sharp ) is a multi-paradigm programming language encompassing strong typing , imperative , declarative , functional , generic ...

1753 - Wikipedia, the free encyclopedia
Language: English Afrikaans አማርኛ العربية Aragonés Asturianu Aymar aru Azərbaycanca বাংলা Bân-lâm-gú Basa Banyumasan Беларуская ‪Беларуская (тарашкевіца)‬ ...

Coded Smorgasbord: Schizophrenic Haiku Comments and More
... writes Malcom StandardResponse UnSubscribeNewsletterUserAccount( string opTinGUID,string email, string sellingRegion, string source, DateTime ...

Limburg.be - Welkom op de site van de provincie Limburg - Welkom_op_de_site_van_de_provincie_Limburg
visit wonen werken leven ontspannen infopunt home op trefwoord contactpersonen wegwijs sitemap print deze pagina Je bent hier: limburg.be Contact ...

Simples Ideias. Por Nando Vieira.
Simples Ideias Siga-me no Twitter Junho/2012 Usando o Vagrant como ambiente de desenvolvimento no Windows http://simplesideias.com.br/usando ...

Resources last updated: 12/6/2015 2:20:18 PM