i am having problem with my retrieving of date after the date fall after 12. for example : if i click from the calander extender: 2/7/2013 to 19/july/2013 , is will throw it me with this error : The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
this is my code.
var format = "MM/dd/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
if (two >= one)
{
SqlConnection conn = new SqlConnection("Data Source=""catalog="";Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT Name,CLass, NRIC, StallNo, AmountSpent ,TimeDate=convert(nvarchar,timedate,103) FROM StudentTransactions WHERE TimeDate BETWEEN '" + one + "' AND '" + two + "'", conn);
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.DataBind();
conn.Close();
}
try this
select CONVERT(varchar,<datecol>,103) --- and will return as dd/mm/yyyy
where convert(date,<datecol>) between '' and ''
If you want to alter the format of a column of a GridView from CodeBehind Add a RowDataBound to your grid view.
Then in the GridView_RowDataBound(object sender, GridViewRowEventArgs e) method, you'll be able to access e which will provide you with access to the individual cells of that row where you can specify a format.
Reference
Reference2
Make sure first that the date part of your TimeDate column is in your desired format, i.e., "dd/mm/yyyy".
var format = "dd/mm/yyyy";
DateTime one = DateTime.ParseExact(startdate, format, CultureInfo.InvariantCulture);
DateTime two = DateTime.ParseExact(enddate, format, CultureInfo.InvariantCulture);
EDIT:
To format the output, you can do ff:
Assuming you have a Boundfield on your TimeDate on your GridView1:
<asp:BoundField DataField="TimeDate" HeaderText="TimeDate" DataFormatString="{0:dd/MM/yyyy}" />
You can also use DataFormatString="{0:d}" to output the date in the short date format of your current culture.
Related
My .aspx markup:
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" PopupButtonID="imgpopup" runat="server" TargetControlID="TextBox11" Format="MM-yyyy" DefaultView="Months" />
<asp:TextBox ID="TextBox11" runat="server">
</asp:TextBox>
.aspx.cs code behind:
string text = "Textbox11.Text";
string s = "SELECT * FROM Stock WHERE MONTH(Date) = 09 AND YEAR(Date) = 2018";
SqlCommand cmd = new SqlCommand(s, conn);
SqlDataAdapter dr = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
dr.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
This is the query I got everywhere on net, but I don't want to specify the fixed date.... I want to allow the user to select text and according to that date select query should work
Please help me with is problem, as I'm new here.
Please forgive me if I asked the same question again which was asked previously by someone else
I suggest a parameterized query with an inclusive start date and exclusive end date for date range queries. It is best to avoid applying functions to SQL Server columns in a WHERE clause as that prevents indexes (if any) from used efficiently. For example:
var date = DateTime.Now;
if(!DateTime.TryParse(Textbox11.Text, out date))
{
//invalid date handing
return;
}
var startDate = new DateTime(date.Year, date.Month, 1);
var endDate = startDate.AddMonths(1);
string s = "SELECT * FROM Stock WHERE Date >= #StartDate AND Date < #EndDate;";
SqlCommand cmd = new SqlCommand(s, conn);
SqlDataAdapter dr = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = endDate;
DataTable dt = new DataTable();
dr.Fill(dt);
Also, consider specifying an explict column list with only those columns needed rather than SELECT * as that will reduce unnecessary data transfer and give SQL Server more query optimization options.
Be aware that freeform date parsing is ambiguous. It would be better to restrict user input to a specific date format or use a date picker control that does that for you, allowing TryParseExact on the server side.
I am trying to fetch number of records for a particular date by feeding the calender extender selection into a textbox and fetching the corresponding count from the database. The datatype of the checkdate column is DateTime. We tried :
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string result = "select count(*) from <TableName> where Checkdate= GETDATE() and sub_code=#sub_code";
SqlCommand cmd = new SqlCommand(result, connection);
connection.Open();
Label3.Visible = true;
Label3.Text = cmd.ExecuteScalar().ToString();
connection.Close();
}
}
protected void Button1_Click(object sender, EventArgs e) {
Label5.Visible = true;
Label3.Visible = true;
string query = "select count(*) from <TableName> where Checkdate= #checkdate and sub_code=#sub_code";
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("#checkdate", tbdate.Text);
connection.Open();
Label5.Text = cmd.ExecuteScalar().ToString();
connection.Close();
}
But I get the Following error :
The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
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 nvarchar data type to a datetime data type resulted in an out-of-range value.
Source Error:
Line 125: connection.Open();
Line 126:
Line 127: Label5.Text = cmd.ExecuteScalar().ToString();
Line 128:
Line 129: connection.Close();
The format of the date stored in DB is as :2018-04-24 12:00:22.803
You have at least two issues here.
First, in the button click event, you have the line
cmd.Parameters.AddWithValue("#checkdate", tbdate.Text);
This is putting the visual (text) representation of the date as a text string into the parameter - you need the date as a date, not the text display of it. This is why you are getting the conversion error. The comments on your question discussed this, so this may already be fixed.
Secondly, in both the SQL queries, you are not checking the date correctly, which is why you are getting the zero count. In the button click query you have "where Checkdate= #checkdate". You said checkdate is a datetime, with a time portion of 12:00 in the example. Your date coming from the program has no time section, (or really it has a time of 00:00), so you are not going to match. you need to check against just the date part of checkdate, like "where CAST(Checkdate as date) = #checkdate".
In the page load, you have same issue but on both sides; you have "where Checkdate= GETDATE()". Getdate returns a time as well, so you won't load anything that was not created the same millisecond you do the page load. You need "where Cast(Checkdate as date) = Cast(GETDATE() as date)"
I managed to resolve the issue by the following approach where I just save the date part of get date as : checkdate= convert(date, GETDATE())
and then call it like this :
SqlCommand cmd = new SqlCommand(query, connection);
string textboxdate = tbdate.Text;
DateTime lastdate = DateTime.ParseExact(textboxdate,
"dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
string newFormat = lastdate.ToString("yyyy-MM-dd");
cmd.Parameters.AddWithValue("#checkdate", newFormat);
connection.Open();
Label5.Text = cmd.ExecuteScalar().ToString();
connection.Close();
I 'am trying to create a vacation planner in asp.net with a SQL Server Express database.
When you add a vacation, you have to add a begintime, endtime and of course who you are.
Is there a way to show an error when there is already vacation with the same time and the same employee as the one they try to add.
This way the system will prevent double vacations. Otherwise Gridview table shows two the same name in two rows with the same days. I want to prevent people from double booking.
Let's say Person A has already booked StartDate = 2016-03-06 and EndDate = 2016-03-10. Than means I want to prevent someone else to book the same StartDate, EndDate, between start and end date, not even earlier date and date between start and end date, I mean for example between 2016-03-01 and 2016-03-06 , 2016-03-07, 2016-03-08... because those dates are between start and end dates.
I tried to create a method like following and then I don't know what to do. I would appreciate for any help
// Noe edited to insert button instead method:
protected void btnInsertVacation_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["ResursplaneringConnectionString"].ConnectionString;
TextDateTime.Text = Calendar1.SelectedDate.ToShortDateString();
using (SqlConnection con = new SqlConnection(cs))
{
string check = "SELECT EmployeeId, StartDate, EndDate FROM vacation WHERE (EmployeeId = #EmployeeId) AND(StartDate <= #NewEndDate) AND(EndDate >= #NewStartDate)";
SqlCommand cmd = new SqlCommand(check, con);
cmd.Parameters.AddWithValue("#EmployeeId", DropDownEmployee.SelectedValue);
cmd.Parameters.AddWithValue("#NewEndDate", txtStartDate.Text);
cmd.Parameters.AddWithValue("#NewStartDate", txtEnd.Text);
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr.HasRows)
{
Response.Write("Dubbel booking");
}
else
{
string insertVacation = "INSERT INTO Planering (StartDate, EndDate, EmployeeId ) VALUES (#StartDate, #EndDate, #EmployeeId)";
SqlCommand cmd2 = new SqlCommand(insertVacation, con);
SqlParameter paramPlaneringStart = new SqlParameter("#StartDate", txtStartDate.Text);
cmd2.Parameters.Add(paramPlaneringStart);
SqlParameter paramPlaneringEnd = new SqlParameter("#EndDate", txtEnd.Text);
cmd2.Parameters.Add(paramPlaneringEnd);
SqlParameter paramEmployeeId = new SqlParameter("#EmployeeId", DropDownEmployee.SelectedValue);
cmd2.Parameters.Add(paramEmployeeId);
con.Open();
cmd2.ExecuteNonQuery();
}
}
}
}
}
For some clarity, let's name the arguments of your method NewStartDate and NewEndDate, to avoid confusion with StartDate and EndDate we'll use for the columns in the database table.
What you want to do in your SQL query is:
SELECT EmployeeId, StartDate, EndDate FROM vacation
WHERE
(EmployeeId = #EmployeeId)
AND (StartDate <= #NewEndDate) AND (EndDate >= #NewStartDate)
Try to draw possible overlapping as segments on a piece of paper, and you should see this will do it.
If this returns any rows, do not allow to create the new booking.
I want to import date value from excel cell. cell value having "10 October 2013" format. I want to convert it to datetime data type. My code getting error "string was not recognized as a valid datetime"
//code
OleDbCommand olecmd = new OleDbCommand("select * from [Sheet1$]", olecon);
OleDbDataReader olerdr = olecmd.ExecuteReader();
while (olerdr.Read())
{
deldate = olerdr.GetValue(13).ToString();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["irisdb"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("procdamandrugs", con);
cmd.CommandType = CommandType.StoredProcedure;
DateTime dt = DateTime.ParseExact(deldate, "MM/dd/yyyy", CultureInfo.InvariantCulture);//getting error in this line
SqlParameter par9 = new SqlParameter();
par9.ParameterName = "#deleffdate";
par9.SqlDbType = SqlDbType.DateTime;
par9.Value = dt;
cmd.Parameters.Add(par9);
cmd.ExecuteNonQuery();
}
}
Do any one help me to solve this issue.
cell value having "10 October 2013" format.
You are giving wrong format in ParseExact that does not match with the date string you are passing. You need different format than you gave. For day you need dd, for month you need MMMM and for year you need yyyy and you have to give spaces as separator.
It is worth the article Custom Date and Time Format Strings on MSDN for using the string formats for date conversion.
DateTime dt = DateTime.ParseExact(deldate, "dd MMMM yyyy", CultureInfo.InvariantCulture);
I recommend the utilizing the DateTime.TryParse method before constructing your SQL objects. Ensure you have quality input before having a conversation with your database.
http://msdn.microsoft.com/en-us/library/ch92fbc1%28v=vs.110%29.aspx
Below is a sample from my own code for an asp.net application
// Validation
DateTime dtOut_StartDate;
if (!DateTime.TryParse(txtStartDate.Text, out dtOut_StartDate))
{
Message = "Start date is not a valid format.";
txtStartDate.CssClass = ErrorCssClass.TextBox;
txtStartDate.Focus();
return false;
}
Select Date Time setting from Right lower bottom & Change the format from here......
I am using the Calendar extender to extend a textbox in ASP.NET inside of Visual Studio 2010. I am trying to insert the date of an event into the database along with other bits of information. I am receiving the "Data type mismatch in criteria expression" error when trying to insert into the database.
I tried using DateTime.ParseExact to convert the string date to Access Date/Time but still no luck.
Here is my code behind:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values (#f1,#f2,#f3,#f4)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_eventtitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_eventdescription.Text)
cmd.Parameters.AddWithValue("#f3", DateTime.ParseExact(tb_eventdate.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture))
cmd.Parameters.AddWithValue("#f4", dd_eventcategory.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/calendar.aspx")
End Sub
Here is my ASP.NET code (notice that I am also formatting the date inserted into the textbox by the CalendarExtender as "dd/MM/yyyy"):
<asp:TextBox ID="tb_eventdate" runat="server" ToolTip="Enter a
date"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="tb_eventdate_CalendarExtender" Format="dd/MM/yyyy" runat="server"
TargetControlID="tb_eventdate">
</ajaxToolkit:CalendarExtender>
The field in my Access database is of type "Date/Time".
I don't know why I am having this problem as I have managed to retrieve dates from the database in another function and converted them ToString:
Function GetEventListing(selectedDay As DateTime) As DataTable
'--read event listing for the given day from an Access query
Dim con As OleDbConnection = GetConnection()
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.CommandText = String.Format("Select * from EventInfo Where EventDate >= #{0}# And EventDate < #{1}#", _
selectedDay.ToString("dd/MM/yyyy"), _
selectedDay.AddDays(1).ToString("dd/MM/yyyy"))
Dim ds As DataSet = New DataSet()
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
da.Fill(ds)
con.Close()
Return ds.Tables(0)
End Function
What could be the cause of the error I am receiving?
Maybe it's not the date that's messing you up. I thought perhaps you were getting the error because you were adding a DateTime value as a parameter (instead of a date converted to a string formatted as yyyy-mm-dd or m/d/yyyy), but I tried the following in C# and it worked fine...
static void Main(string[] args)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Administrator\Desktop\Database1.accdb;");
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Events (EventName, EventDate) VALUES (?, ?)", conn);
cmd.Parameters.AddWithValue("?", "TestEvent");
cmd.Parameters.AddWithValue("?", (new DateTime(2013,3,21)));
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Done.");
}
...so if your DateTime parsing is returning a valid DateTime value then it looks like your query should work.
If it really is the execution of the SQL statement that is failing, the only other likely suspect is the dd_eventcategory.SelectedValue. Perhaps that needs to be .ToString()'d...?