How to solve this error "String was not recognized as a valid DateTime " - asp.net

Hello
I am using datetime datatype in sql sever but whenever i save this form i am getting this error "String was not recognized as a valid DateTime" . In my code i am using ajax code on textbox to select date . But same error i am getting . I am specify date format into it but still it get error . What we do now.

Try Format:
DateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

you can use this vb code to convert it :
dataandtimevarible.Value.ToString("dd-MM-yyyy")
you need to add Format="dd-MM-yyyy" to your mark up code and add this one to your markup Code
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" Format="dd-MM-yyyy" TargetControlID="CreatedOnTextBox">
</ajaxToolkit:CalendarExtender>
last thing you have to make sure from the Culture language!!!

How are you saving your data into the database? Are you using parameters? If not then use parameters - to save date/time value, choose your parameter data type as DbType.DateTime.
Now, your text box will give you a string value and you need to convert it to date/time data type before assigning to the parameter. Use DateTime.ParseExact method with your specific date format - for example,
var param = new SqlParameter("MyDateColumn");
param.DbType = DbType.DateTime;
param.Value = DateTime.ParseExact(textbox1.Text, "dd-MM-yyyy", null);

Related

Selecting values between 2 dates

I am currently working on a website that offers tutoring services and I have been stuck on this issue quite a while..
I have 2 text boxes where the user chooses a start date and a finish date, when the user clicks view he would be suppose to see the results in a gridview. I am using FormParameters to insert the date into the query.
SelectCommand of the sqldatasource
SelectCommand="SELECT [Session].Session_num AS Num, [Session].Session_Time_Stamp AS Session_Date, Student.Student_First & ' ' & Student.Student_Last AS Student FROM (([Session] INNER JOIN Student ON [Session].Student_Num = Student.Student_Num) INNER JOIN Class ON [Session].Class_ID = Class.Class_ID) WHERE ((([Session].Session_Time_Stamp) Between #firstdate And #seconddate))">
Parameters of the SqlDataSource
<SelectParameters>
<asp:FormParameter Name="firstdate" Type="DateTime"/>
<asp:FormParameter Name="seconddate" Type="DateTime"/>
</SelectParameters>
This is executed when the user clicks the view button, it is where I set the values of the parameters and execute the sql select.
Dim fdate As DateTime = Format(CDate(txtStartDate.Text), "MM/dd/yyyy")
Dim ldate As DateTime = Format(CDate(txtEndDate.Text), "MM/dd/yyyy")
gridTutor.SelectParameters("firstdate").DefaultValue = fdate
gridTutor.SelectParameters("seconddate").DefaultValue = ldate
gridTutor.Select(DataSourceSelectArguments.Empty)
gridTutorSessions.DataBind()
fdate and ldate are not empty, however after this is executed the query result is empty. Could it be that wrong methods to execute the select?
Edit: I realized the problem is probably with the query and DateTime format. When I transformed my textbox value to DateTime it put it like this #2/20/2014#. However, it doesn't return anything even if there are values between the two dates.
If anybody have an access query with DateTime I would like to see it. Thanks
I managed to fix it by formatting the date in my access database it's not the best solution but it is a fix for the situation
I believe you need to manually set fdate and ldate just before you do your 'selectparameters' (i.e. use "fdate = Format(CDate(txtStartDate.Text), "MM/dd/yyyy")". According to the following, values asigned to Dim in the manner you have would not reflect the realtime values you want. See the following regarding VB: "You can assign a value to a variable when it is created. For a value type, you use an initializer to supply an expression to be assigned to the variable. The expression must evaluate to a constant that can be calculated at compile time.

I want to get only year/month/day in a correct format from my datatime type field in my table in SQL Server

I have table in SQL Server it has a orderDate column with datetime type
I use using System.Globalization in my asp.net page and use this code to get my system date history of solar format like this 1391/01/29 year/month/day:
PersianCalendar pc=new PersianCalendar();
DateTime dt = DateTime.Now;
string year= pc.GetYear(dt).ToString();
string month= pc.GetMonth(dt).ToString();
string day= pc.GetDayOfMonth(dt).ToString();
and it works fine and then I store the date in my table and then write a select query in SQL Server it works fine but when I get this column value and show it in my grid view which uses SqlDataSource in another asp.net page it shows the result like this :
AM 12:00:00 9/1/1391
But it should show the result like
1391/09/01
I don't know why this happen?
Set the DataFormatString property on the bound field:
<asp:BoundField DataField="<Your Date Field>" HeaderText="<Column Header>"
DataFormatString="{0:yyyy-MM-dd}" />
Or you can convert date value on server before passing to application.
SELECT replace(convert(varchar(10),getdate(),120),'-','/') date

How change the format DateTime of a column in DataTable from c#

In DataTable i have this format mm/dd/yyyy hh:mm:ss AM
I want to change format to "dd.MM.yyyy"
foreach (DataRow dr in dt.Rows)
{
dr["birth_day"]= String.Format("{0:dd.MM.yyyy}",dr["birth_day"]);
}
It gave me this error:
String was not recognized as a valid DateTime.Couldn't store <25.04.1988> in birth_day Column. Expected type is DateTime.
String format needs more than one argument, one for the string, and 1-n for each variable you have in the string.
e.g.
dr["birth_day"]= DateTime.Parse(String.Format("{0}:dd.MM.yyyy",dr["birth_day"]));
Though i am still not sure this would give what you want
It's saying you have not provided and argument for the place holder {0} as in
dr["birth_day"]= DateTime.Parse(String.Format("{0}:dd.MM.yyyy",SomeValuethatgoesbeforethe colon));
However your code makes no sense at all, where's the date that's meant to be parsed?

ASP.NET how to convert string to Date without forward slashes

Just wondering how I can convert the following string into a datetime 111222, at the moment it is telling me that this is not a valid datetime value..
You can use the DateTime.ParseExact method and supply the format your input is in.
Edit - added code:
DateTime dt = DateTime.ParseExact("111222", "yyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString());

Passing Multiple values Through Query String?

I tried to pass more than one value through Query String from page1.aspx to page2.aspx.
This is my Query string in the Grid View
<a href="javascript:void(0);" onclick='javascript:window.open("Update.aspx?Regno= <%#Eval ("ID") %>'+ ","'&Fn=<%#Eval ("FIRSTNAME") %>' +", "'&Ln=<%#Eval ("LASTNAME") %>'")';>
Edit</a>
On My Page2.aspx, my code behind on PageLoad is:
if (Page.IsPostBack) return;
string id = Request.QueryString["ID"];
string Firstname = Request.QueryString["FIRSTNAME"];
string LastName = Request.QueryString["LASTNAME"];
My Visual Studio IDE shows a syntax error on this query string. I dont know the exact way to pass multiple values through Query String. How to make it work? Can anyone pls help me on this..
Which is the right syntax to pass multiple query string?
You use the & to seperate multiple query string cars. For example, Foo=12&first=death
("LASTNAME") %>'")' ;
Whats up with the semicolon here at the end???
try removing that as u dont need it
Also
You string is a bit difficult to find any missing , quotes. Better print in console , or give an alert for this
Update.aspx?Regno= <%#Eval ("ID") %>'+ ","'&Fn=<%#Eval ("FIRSTNAME") %>' +", "'&Ln=<%#Eval ("LASTNAME") %>'")';
And copy the printed string, paste it in the Browser and check whether it works! There by u can see what are all the things getting passed and where you made mistake in syntax

Resources