Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get my datetime from database, into the variable datetime "dat", however, the current code throws a compiling error of ---> Use of unassigned local variable 'dat'
C#
public static string content()
       {
           string xml = "";
           string title = "";
           string content = "";
           DateTime dat = new DateTime();

           SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["#######"].ConnectionString);
           string commandtext = "###########";
           SqlCommand command = new SqlCommand(commandtext, con);
           con.Open();
           command.Parameters.Add(new SqlParameter("title", title));
           command.Parameters.Add(new SqlParameter("Body", content));
           command.Parameters.Add(new SqlParameter("ACTIVEDATE", dat));

           SqlDataReader reader = command.ExecuteReader();

           dat.ToString("dd-MM-yyyy");

           //XElement code

           while (reader.Read())
           {
               string top = reader.GetString(0);
               string dtt = reader.GetString(1);
               string body = reader.GetString(2);

               var result = top + "<br />" + dtt + "<br />" + body + "<br />";

               string data = result.ToString();

               xeSendTo1.Add(new XElement("value", (new XCData(data))));

           }
           con.Close();

           return xml = xDoc.ToString();
       }

I tried changing the assignment statement to the following, but they further resulted in more compiling errors.

DateTime dat = new DateTime();<br />
<br />
DateTime.TryParseExact(...)


is their a correct approach to declare the Datetime variable, for the sqlParameter.

Please advice.

Many thanks
Posted
Comments
[no name] 14-Oct-14 11:39am    
DateTime dat = DateTime.Now;
Maciej Los 14-Oct-14 11:42am    
Wes, why don't you post it as an answer?
miss786 14-Oct-14 12:26pm    
Thank you very much for your help. =D

Quote:
dat.ToString("dd-MM-yyyy");
Is the problem. It doesn't do anything.

Remove that code and inside your while loop do:

C#
dat = DateTime.Parse(reader["dateField"].ToString());


Or even use TryParse to be more accurate.
 
Share this answer
 
Quote:
Use of unassigned local variable 'dat'
The message is clear enough. You are trying to use something, which is not assigned yet. Here is "dat".

So, assign some value to it. Then read.

I guess you should read the database DateTime field inside the while loop as Ryan suggested.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900