I am using a custom ASP.NET control that I found here: http://www.codeproject.com/Articles/5347/DataCalendar
I have used one of the templates in the source file download-able from the page above as a starting point for my custom calendar. My aim is to only display events that the current user has created. I am doing this by creating a session variable called "userName" and I am parameterizing it in a query like so:
Function GetEventData(startDate As DateTime, endDate As DateTime) As DataTable
'--read data from an Access query
Dim con As OleDbConnection = GetConnection()
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.Parameters.AddWithValue("#currentUser", Session("currentuser"))
cmd.CommandText = String.Format("Select EventDate, CreatedBy, Count(*) From EventInfo Where (CreatedBy = #currentUser) and EventDate >= #{0}# And EventDate <= #{1}# Group By EventDate", _
startDate, endDate)
Dim ds As DataSet = New DataSet()
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
da.Fill(ds)
con.Close()
Return ds.Tables(0)
End Function
Unfortunately I am receiving this error:
Parameter[0] '' has no default value.
I have ensured that I am logged in so it is not a problem of there being no value for User.Identity.Name (I don't think). I am creating the session variable in the Page Load sub:
Sub Page_Load(o As Object, e As EventArgs)
Session("currentuser") = User.Identity.Name
End Sub
So, what's going wrong?
From MSDN :
The OLE DB.NET Provider does not support named parameters for passing
parameters to an SQL Statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter.
Try:
cmd.CommandText = String.Format("Select EventDate, CreatedBy, Count(*) From EventInfo Where ([CreatedBy = ?]) and EventDate >= #{0}# And EventDate <= #{1}# Group By EventDate,CreatedBy", startDate, endDate)
Related
I will try to keep this as brief as possible.
I have a function called GetData(ByVal query As String) whose sole purpose is to populate a data table multiple times based on certain conditions. As you can see, the function accepts a string variable where the SQL statement resides. What I am trying to do is add a scalar variable, "#date" in my case, and no matter where I try to add this variable it throws an error stating "Must declare scalar variable #date.
Edit: I should mention that it is throwing the "must declare variable" error on the sda.Fill(dt) line.
GetData Function
Private Shared Function GetData(ByVal query As String) As DataTable
Dim constr As String = ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
Dim dt As DataTable = New DataTable()
cmd.Parameters.Add("#date", SqlDbType.Date).Value = Date.Today
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
cmd.Parameters.AddWithValue("#date", Date.Today)
sda.Fill(dt)
End Using
Return dt
End Using
End Using
End Function
I am calling the function in a procedure that has the query and handles all of the conditions I need.
Procedure
Dim queryStart As String = "SELECT ( SELECT SUM(DealerNet) FROM Agreement WHERE VoidDate IS NULL "
Dim queryAlias As String = "AS Actual, "
Dim queryStart2 As String = "(SELECT SUM(Amount) FROM AccountingUS.dbo.ProjectedSales "
Dim queryAlias2 As String = "AS Projected "
If chart = "pmtd" Then
Dim queryCondition As String = "AND IssueDate BETWEEN (SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, #date)-1, 0)) AND #date) "
Dim queryCondition2 As String = "WHERE [Month] = MONTH(#date) AND [Year] = YEAR(#date)) "
Dim query As String = queryStart + queryCondition + queryAlias + queryStart2 + queryCondition2 + queryAlias2
Dim xMember1 As String = "Actual"
Dim xMember2 As String = "Projected"
Dim dt As DataTable = GetData(query)
pmtdChart.DataSource = dt
The variable in question is the #date variable in the strings within the "If" statement, the only value it holds is todays date. Currently, I have tried to use "cmd.Parameters.Add("#date", SqlDbType.Date).Value = Date.Today in the GetData function, however, I still receive the same "Must declare scalar variable" error. I have also tried replacing the #date variable with simply "" + Date.Today + "" or a variable that holds todays date, but upon doing so I receive an operand error about "Operand Clash: Date is incompatible with Int"
Any help regarding this issue would be greatly appreciated, I am relatively new to programming and would appreciate any tips or criticisms regarding best practices. If you need any additional information or clarification regarding this issue I would be happy to provide what I can. Thank you in advance.
Ok, a few things:
I would actually pass a command object to that get data routine.
And your issue is you feeding the query to the "adaptor", but NOT supplying the #date parameter to that "sda"
this:
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
cmd.Parameters.AddWithValue("#date", Date.Today)
sda.Fill(dt)
End Using
In other words, you NOT EVEN using the cmd object!!!
So, you would need to add the parameter's to the sda object!!
eg this:
Public Function GetData(ByVal query As String) As DataTable
Dim dt As DataTable = New DataTable()
Dim constr As String =
ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
sda.SelectCommand.Parameters.Add("#date", SqlDbType.Date).Value = Date.Today()
sda.Fill(dt)
End Using
End Using
Return dt
End Function
So, yes, you WILL get that error about "#date" not being declared, since you NOT using the cmd object to fill the table, but are using the data adaptor.
So, as a future suggest?
Pick one way, or the other way.
I MUCH over the years have decided that I will use/have/adopt and cookie cut over and over the SqlCommand object.
I find the Sql cmd object better, since:
it has the parameters.
it has a connection object (if you want to use)
it has a data reader built in
So, what this means?
I suggest this code for get data:
Private Shared Function GetData(ByVal query As String) As DataTable
Dim constr As String =
ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString
Dim dt As DataTable = New DataTable()
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query, con))
con.Open()
cmd.Parameters.Add("#date", SqlDbType.Date).Value = Date.Today
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
So, we don't need a data adaptor. In fact, you only need a adaptor if you going to update the resulting table (think a "adaptive" table to remember this). You not going to update the data, so really, no need to use a "adaptor" at all here. (and sadly, far too many examples use a "adaptor" anyway. They are for ALLOWING update of the data table, and you not doing that!
So, use a command object. Do note that you ALWAYS must then open the confection, but since we have "using" blocks, it will ALWAYS be closed for you.
And note how then we don't create to "use" the "reader" from the adaptor, nor a fill command. (so, we eliminated one whole confusing object!!).
So, in your example, you created a SQL command object, correctly added the parameter to the command object, but THEN DON'T use it, and then decided to create a data adaptor, and use that!!!
So, you could/can leave your code as you had with the sda "prameter " fix I posted above.
However, but I think your better off to use a sql command object.
Note even better?
Pass the command object to the GetData routine.
I have a global "general" purpose routine called MyRstP(), and I pass it a command object, even for just plain jane sql.
but, if you decide to add parameter's, you can!
Do note that parameter's can be added 100% independent of the SQL string, and they can be added before, or after you set the sql string.
And you can add parameter's WITHOUT a valid working connection (or have created one just yet). So, "parameters" are just a colleciton - it does not care about the SQL (well, at least not yet!!).
So, here is my RstP, and I dumped this into a plain jane "module1" which VB has (this means you don't have to create a static class, and this works then just like VB6, or VBA.
So, this:
Public Function MyRstP(cmdSQL As SqlCommand, ByVal Optional strCon As String = "") As DataTable
If strCon = "" Then
strCon = My.Settings.TEST4
End If
Dim rstData As New DataTable
Using conn As New SqlConnection(strCon)
Using (cmdSQL)
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
So, now to say fill a grid view, I use this:
Dim strSQL As String =
"SELECT id, HotelName, City FROM tblHotelsA"
Dim cmdSQL As New SqlCommand(strSQL)
GridView1.DataSource = MyRstP(cmdSQL)
GridView1.DataBind()
or say a given date of some such:
How about all hotel visit dates from start of year.
So, this:
Dim strSQL As String =
"SELECT id, HotelName, City FROM tblHotelsA
WHERE VisitDate >= #dtStart"
Dim dtStart As DateTime
dtStart = DateSerial(DateTime.Today.Year, 1, 1)
Dim cmdSQL As New SqlCommand(strSQL)
cmdSQL.Parameters.Add("#dtStart", SqlDbType.DateTime).Value = dtStart
GridView1.DataSource = MyRstP(cmdSQL)
GridView1.DataBind()
note then how I have that MyRstP (like your get data), but I can pass it quite much anything I want, including parameter's from the "calling" code, NOT in that general routine.
Anyway, the above use and adding the parameter's to the "adaptor" will fix this, but I would change over to using just a command object and a connection - the adaptor really not required, and as noted, they really are to be used WHEN you actually want to update the data table, and then send it back to the database in one shot.
If you look closely, you setup a cmd command, but you never actually pass it to the DataTable. So it doesn't know anything about your params.
How about this instead (copied untested from Trying to pass SqlCommand in SqlDataAdapter as parameters):
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#date", SqlDbType.Date)
cmd.Parameters.AddWithValue("#date", Date.Today)
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
Dim dt as new DataTable()
using db as new SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ConnectionString)
db.Open();
using cmd as New SqlCommand(query, con)
cmd.Parameters.Add("#date", SqlDbType.Date).value = Date.Today
//cmd.Parameters.AddWithValue("#date", Date.Today)
using adp as new SqlDataAdapter(cmd)
adp.Fill(dt)
return dt
End using
End using
End using
I need pass the whole table to a stored procedure to run a update query.
This is my code:
CREATE TYPE [dbo].[UploadData] AS TABLE
(
[CODE] [varchar](4) NULL,
[SERIALNUMBER] [varchar](20) NULL,
[PRODUCTCODE] [varchar](20) NULL,
[THRESHOLD] [int] NULL
)
This is my stored procedure:
CREATE PROCEDURE sp_UpdateExchangeThreshold
#TableType dbo.UploadData READONLY
UPDATE [dbo].[ExchangeData_20221213]
SET t.Threshold = tbl.THRESHOLD
FROM [dbo].[ExchangeData_20221213] t
INNER JOIN #TableType AS tbl ON t.ProductCode = tbl.PRODUCTCODE
AND t.SerialNumber = tbl.SERIALNUMBER
In my VB.Net code, I have this:
Using sqlCommand As SqlCommand = New SqlCommand()
sqlCommand.Connection = connection
sqlCommand.CommandText = "sp_UpdateExchangeThreshold"
sqlCommand.CommandTimeout = 180
sqlCommand.CommandType = CommandType.StoredProcedure
Dim parameterList As SqlParameter = New SqlParameter("#TableType", SqlDbType.Structured)
parameterList.Value = dataTable
parameterList.Direction = ParameterDirection.Input
sqlCommand.Parameters.Add(parameterList)
sqlCommand.ExecuteNonQuery()
End Using
I'm not able to update the records. Any mistake I made? Please help
Unfortunately, a .NET ADO datatable is NOT a SQL Server table type. They have NOHTING to do with each other. You can use a datatable with Oracle, MySQL, or any server based system. You can even use a access database with a data table.
So, datatable object is platform gnostic (neutral), and thus can't be passed, used as a SQL table type.
However, you don't really have to pass a table back. The REAL question is what do you want to do with this table?
Do you want to edit, or update or insert rows from that table back into the database?
If yes, then use a table adaptor (that's what they are for).
Not only will they do all the dirty work for you, but that table can have updates, deletes, edits and insert/additions.
And with ONE command you can send that WHOLE table + all edit/update/delete/adds in one shot.
Say like this:
Dim rstHotels As New DataTable
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT * FROM tblHotelsD"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
' delete first row
rstData.Rows(0).Delete() ' delete first row
rstData.Rows(2).Item("City") = "Zoo" ' edit/modify the 3rd row
Dim OneNewRow As DataRow = rstData.NewRow
OneNewRow("FirstName") = "First Name"
OneNewRow("LastName") = "last Name"
OneNewRow("HotelName") = "My Hotel Name"
OneNewRow("Active") = True
rstData.Rows.Add(OneNewRow)
' now, lets send edits/delete/inserts back to database.
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
da.Update(rstData)
End Using
End Using
Now, I have the load the table and the update as per above, but they can be done separately.
Edit: Sending the datatable to SQL Server, but not all rows.
' so, lets "send" to the sql database some data
Dim rstData2 As New DataTable
rstData2.Columns.Add("HotelName", GetType(String))
rstData2.Columns.Add("City") ' FYI -- defualt is string
rstData2.Columns.Add("Active", GetType(Boolean))
' lets create 5 test rows of data
For i = 1 To 5
Dim MyNewRow As DataRow = rstData2.NewRow
MyNewRow("HotelName") = "Hotel #" & i
MyNewRow("City") = "City #" & i
MyNewRow("Active") = True ' you MUST include columnes that require deffault value
rstData2.Rows.Add(MyNewRow)
Next
' now send in one shot to database
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT ID, HotelName, City, Active FROM tblHotelsD"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim da As New SqlDataAdapter(cmdSQL)
Dim daU As New SqlCommandBuilder(da)
da.Update(rstData2)
End Using
End Using
I have this form ASP.NET that have two textbox and a label, where the user enters only the expiration date in the last textbox, while the others are inserted automatically if the user clicks on another button inside the repeater where the customer code and company name are found.
The problem is that I created a class to do the insertion: I used a stored procedure for the insertion and I used the query parameterization.
When I parse the code and date it gives me 0 and a default date as a result, while my goal is to insert them into a table inside a db and then have it displayed inside the repeater.
P.S. I add that for reading the data I have another class with another stored procedure and that I have some values that are inside another table (the code and the name of the company).
This is the method:
Public Sub INSERT_EXP_DATE_TABLE()
Dim id_customer As Integer
Dim exp_date As Date
Try
cmd.Connection = cn
cmd.CommandType = CommandType.StoredProcedure
MyParm = cmd.Parameters.Add("#COD_CUSTOMER", SqlDbType.Int)
If (Integer.TryParse(txt_COD_CUSTOMER.Text, id_customer)) Then
MyParm.Value = id_customer
Else
MsgBox("customer not found", vbCritical)
End If
MyParm = cmd.Parameters.Add("#COMPANY_NAME", SqlDbType.NVarChar)
MyParm.Value = lbl_COMPANY_NAME.Text.ToString
MyParm = cmd.Parameters.Add("#EXP_DATE", SqlDbType.Date)
If (Date.TryParse(txt_EXP_DATE.Text, exp_date)) Then
MyParm.Value = exp_date
Else
MsgBox("Exp Date not found", vbCritical)
End If
cmd.CommandText = "LST_INSERT_TABLE_01"
cmd.Connection.Open()
cmd.ExecuteNonQuery()
MsgBox("Date registred", vbInformation)
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
End Sub
And this is the stored procedure:
#ID_CUSTOMER int,
#COMPANY_NAME varchar(50),
#EXP_DATE date,
AS
BEGIN
INSERT INTO TABLE
(
ID_CUSTOMER,
COMPANY_NAME,
EXP_DATE,
)
VALUES(
#ID_CUSTOMER,
#COMPANY_NAME,
#EXP_DATE,
)
END
Keep your connection local to the method where it is used. Connections use unmanaged resources so they include a .Dispose method which releases these resources. To ensure that the database objects are closed and disposed use Using...End Using blocks.
Do you parsing before you start creating database objects. Exit the sub so the user has a chance to correct the problem.
Side note: I don't think a message box will work in an asp.net application.
You set up the company name parameter as an NVarChar but your stored procedure declares it as a VarChar. Which is correct?
It is not necessary to call .ToString on a .Text property. A .Text property is already a String.
You are providing a parameter called "#COD_CUSTOMER" but your stored procedure does not have such parameter.
Public Sub INSERT_EXP_DATE_TABLE()
Dim id_customer As Integer
If Not Integer.TryParse(txt_COD_CUSTOMER.Text, id_customer) Then
MsgBox("Please enter a valid number.", vbCritical)
Exit Sub
End If
Dim exp_date As Date
If Not Date.TryParse(txt_EXP_DATE.Text, exp_date) Then
MsgBox("Please enter a valid date.")
Exit Sub
End If
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("LST_INSERT_TABLE_01", cn)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
.Add("#ID_CUSTOMER", SqlDbType.Int).Value = id_customer
.Add("#COMPANY_NAME", SqlDbType.VarChar, 50).Value = lbl_COMPANY_NAME.Text
.Add("#EXP_DATE", SqlDbType.Date).Value = exp_date
End With
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Sub
{
string CN = Interaction.InputBox("Enter Company Name","Customer","",-1,-1);
string Cname = Interaction.InputBox("Enter Customer Name", "Customer", "", -1, -1);
SqlConnection con = new SqlConnection(#"Data Source=Adnan;Initial Catalog=Production;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO hello(Company_Name,Customer_name ) VALUES ( #Company_Name,#Customer_name )");
cmd.Connection = con;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Company_Name", CN.ToString() );
cmd.Parameters.AddWithValue("#Customer_name", Cname.ToString());
}
I created a stored procedure to include a new user for my system. Parameters are: Name, Mail and Password (all varchar). The stored procedure first checks if the mail is already in the database. If not, then the information in added to the table. At the end, the output is a table with the user data.
CREATE PROCEDURE [dbo].[user_new]
(#name VARCHAR(50),
#mail VARCHAR(50),
#password VARCHAR(100)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #exist INT
SELECT #exist = COUNT([id])
FROM [dbo].[User]
WHERE [mail] = #mail
IF #exist = 0
INSERT INTO [dbo].[User] ([name], [mail], [password])
VALUES (#name, #mail, #password)
SELECT
#exist AS [exist], [id], [name], [mail]
FROM
[dbo].[User]
WHERE
[mail] = #mail
END
GO
When I execute the stored procedure in SSMS, everything works fine: when I insert a new mail, field [exist] returns 0. When I insert a mail that already exist, field [exist] returns 1. So far, so good.
When I execute the stored procedure from my .NET application (which has a lot of other calls that are working fine), the error happen: no matter if I try to add a new or an existing mail, [exist] always returns 1. I tried to change the logic several times, but I always get the wrong result.
Here is the .NET code:
Public Function api_v2_player_new(<FromBody> s As User) As Object
Dim arrParameters(,) As String = {{"#name", s.Name}, {"#mail", s.Mail}, {"#password", s.Password}}
Dim dtc As Data.DataTableCollection = SQL.Execute("dbo.user_new", arrParameters)
Return SQL.toJson(dtc(0))
End Function
Public Class SQL
Public Shared Function runStoredProcedure(ByVal cmd As SqlCommand) As Data.DataTableCollection
Dim spName As String = cmd.CommandText.ToString
cmd.CommandTimeout = 120
Dim cs As String = System.Configuration.ConfigurationManager.ConnectionStrings("csKickerliga").ConnectionString
Dim connection As SqlConnection = Nothing
connection = New SqlConnection(cs)
Dim dt As DataTable = New DataTable()
cmd.Connection = connection
connection.Open()
Dim adp As New SqlDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Return ds.Tables
connection.Close()
End Function
Shared Function Execute(spName As String, arrParameters(,) As String) As Data.DataTableCollection
Dim cmd As SqlCommand = New SqlCommand(spName)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
For i = 0 To (arrParameters.Length / 2) - 1
.AddWithValue(arrParameters(i, 0), arrParameters(i, 1))
Next
End With
Dim dtc = runStoredProcedure(cmd)
Return dtc
End Function
Shared Function toJson(dt As DataTable) As List(Of Object)
Dim oList As New List(Of Object)
Dim o As New Dictionary(Of String, Object)
Dim data As Object
For Each r As DataRow In dt.Rows
o = New Dictionary(Of String, Object)
For Each c As DataColumn In dt.Columns
If IsNumeric(r(c.ColumnName)) Then
If Not r(c.ColumnName).ToString.Contains(".") Then
data = CInt(r(c.ColumnName))
Else
data = r(c.ColumnName).ToString
End If
Else
data = r(c.ColumnName).ToString
End If
o.Add(c.ColumnName, data)
Next
oList.Add(o)
Next
Return oList
End Function
End Class
Found the issue. The code was executing the stored procedure twice:
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Therefore on the recond run the record already existed because it was created on the first run. I removed one of the lines and now it's working!
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...?