help date format in vb.net - vb.net

Dim Con As OleDb.OleDbConnection
Dim Sql As String = Nothing
Dim Reader As OleDb.OleDbDataReader
Dim ComboRow As Integer = -1
Dim Columns As Integer = 0
Dim Category As String = Nothing
Dim oDatumMin As Date
Dim column As String
column = Replace(TxtDateMax.Text, "'", "''")
'oDatumMin = Convert.ToDateTime(TxtDateMin.Text)
oDatumMin = DtpMin.Value
Dim oPath As String
oPath = Application.StartupPath
' Select records.
Con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & oPath & "\trb.accdb;")
Dim cmd As New OleDb.OleDbCommand
'Dim data_reader As OleDbDataReader = cmd.ExecuteReader()
Sql = ("SELECT * FROM " & cmbvalue & " WHERE Datum>='" & oDatumMin & "'")
cmd = New OleDb.OleDbCommand(Sql, Con)
Con.Open()
Reader = cmd.ExecuteReader()
Do While Reader.Read()
Dim new_item As New ListViewItem(Reader.Item("Datum").ToString)
new_item.SubItems.Add(Reader.Item("Steleks i krpe za cišcenje-toal papir-ubrusi-domestos").ToString)
new_item.SubItems.Add(Reader.Item("TEKUCINA ZA CIŠCENJE PLOCICA").ToString)
new_item.SubItems.Add(Reader.Item("KESE ZA SMECE").ToString)
new_item.SubItems.Add(Reader.Item("OSTALO-džoger-spužva za laminat").ToString)
new_item.SubItems.Add(Reader.Item("PAPIR").ToString)
LvIzvjestaj.Items.Add(new_item)
Loop
' Close the connection.strong text
Con.Close()``
when i select table,(cmbvalue) from combobox
and when i select date from datetime picker (dtp) or in last case from texbox converted to date and time sql looks like this "SELECT * FROM Uprava WHERE Datum>='2.6.2010 10:28:14'"
and all query looks ok but am geting
Data type mismatch in criteria expression. error for date (oDatumMin) when excute
column in access is also set to date
i have no idea what else to try

I suspect this is a localisation issue. Try changing the date format to one which should be universally recognised:
SELECT * FROM Uprava WHERE Datum >='2010/06/02 10:28:14'
[What is your server locale/code page?]

Dim sql As String = "SELECT * FROM MyTable WHERE Datum >= ?"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(sql)
cmd.Parameters.Add(New OleDb.OleDbParameter("#Datum", OleDb.OleDbType.Date))
cmd.Parameters("Datum").Value = oDatumMin
http://msdn.microsoft.com/de-de/library/bbw6zyha.aspx

Related

I want to query between two dates in sqlite with two textbox(textbox4.text and textbox5.text = variable) in form

Dim query As String = "select * from mytable where strftime('%Y-%m-%d',tarih) between 'TextBox4.text' and 'TextBox5.text' "
Can not assign query variable ?
Datagridview result = empty
info :Datagridview date format = 2018-01-01 17:42:24
Dim btarihyil As String
btarihyil = DateTimePicker2.Value.ToString.Substring(6, 4)
Dim btarihay As String
btarihay = DateTimePicker2.Value.ToString.Substring(3, 2)
Dim btarihgun As String
btarihgun = DateTimePicker2.Value.ToString.Substring(0, 2)
TextBox4.Text = btarihyil & "-" & btarihay & "-" & btarihgun
Dim bttarihyil As String
bttarihyil = DateTimePicker3.Value.ToString.Substring(6, 4)
Dim bttarihay As String
bttarihay = DateTimePicker3.Value.ToString.Substring(3, 2)
Dim bttarihgun As String
bttarihgun = DateTimePicker3.Value.ToString.Substring(0, 2)
TextBox4.Text = btarihyil & "-" & btarihay & "-" & btarihgun
TextBox5.Text = bttarihyil & "-" & bttarihay & "-" & bttarihgun
Dim Yol As String = "Data Source=database1.s3db;version=3;new=False"
Using MyConn As New SQLiteConnection(Yol)
If (MyConn.State = ConnectionState.Closed) Then
MyConn.Open()
End If
Dim Sorgu As String = "select * from mytable where strftime('%Y-%m-%d',tarih) between 'TextBox4.text' and 'TextBox5.text' "
Using MyCmd As New SQLiteCommand(Sorgu, MyConn)
Dim Da As New SQLiteDataAdapter(MyCmd)
Dim Ds As New DataSet
Dim Dt As New DataTable
Ds.Reset()
Da.Fill(Ds)
Dt = Ds.Tables(0)
Dim Bs As New BindingSource With {.DataSource = Dt}
DataGridView1.DataSource = Bs
Bs.MoveLast()
MyConn.Close()
MyCmd.Dispose()
MyConn.Dispose()
End Using
End Using
End Sub
You are using "TextBox4.Text" and "TextBox5.Text" literally in the query. That will not pass the values of textboxes to the query. So it will result in error.
Also you need to use parameterized query to avoid syntax errors.
Also I am not sure why you are using strftime function. That function is used just for formatting.
Following the code I re-written using parameterzied query approach.
Dim Yol As String = "Data Source=database1.s3db;version=3;new=False"
Using MyConn As New SQLiteConnection(Yol)
If (MyConn.State = ConnectionState.Closed) Then
MyConn.Open()
End If
Dim Sorgu As String = "select * from mytable where tarih between #startDate and #endDate "
Using MyCmd As New SQLiteCommand(Sorgu, MyConn)
Dim startDate as new SQLiteParameter("#startDate")
startDate.Value = DateTimePicker2.Value
Dim endDate as new SQLiteParameter("#endDate")
endDate.Value = DateTimePicker3.Value
MyCmd.Parameters.Add(startDate)
MyCmd.Parameters.Add(endDate)
Dim Da As New SQLiteDataAdapter(MyCmd)
Dim Ds As New DataSet
Dim Dt As New DataTable
Ds.Reset()
Da.Fill(Ds)
Dt = Ds.Tables(0)
Dim Bs As New BindingSource With {.DataSource = Dt}
DataGridView1.DataSource = Bs
Bs.MoveLast()
MyConn.Close()
MyCmd.Dispose()
MyConn.Dispose()
End Using
End Using
This should help you resolve your issue.

Add Column to DataTable before exporting to Excel file

I have a DataTable that is built like this:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Then it is converted to a DataView and exported to Excel like this:
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I want to add another column and fill it with data before I export to Excel. Here's what I'm doing now to add the column:
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
Then to populate it:
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
Dim reader As SqlDataReader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next row
But I get a "System.FormatException: Input string was not in a correct format." error when I run the app. It doesn't seem to like these lines:
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
I think I have more than one issue here because even if I comment out the loop that fills the data in, the column I created doesn't show up in the Excel file. Any help would be much appreciated. Thanks!
EDIT:
Okay, I was grabbing the column name instead of the actual data in the column... because I'm an idiot. The new column still doesn't show up in the exported Excel file. Here's the updated code:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
'set the values of the new column based on info pulled from db
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Dim reader As SqlDataReader
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row.Item(0))
Dim pID As String = row.Item(2).ToString
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
reader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
myConn.Close()
Next row
dt.AcceptChanges()
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I suppose that you want to search your MyTable if it contains a record with the uid and the pid for every row present in your dt table.
If this is your intent then your could write something like this
Dim qry As String = "SELECT UserID FROM [MyTable] WHERE [UserID] = #uid AND [PassID] = #pid"
Using myConn = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Using myCommand = new SqlCommand(qry, myConn)
myConn.Open()
myCommand.Parameters.Add("#uid", OleDbType.Integer)
myCommand.Parameters.Add("#pid", OleDbType.VarWChar)
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row(0))
Dim pID As String = row(1).ToString()
cmd.Parameters("#uid").Value = uID
cmd.Parameters("#pid").Value = pID
Dim result = myCommand.ExecuteScalar()
If result IsNot Nothing Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next
End Using
End Using
Of course the exporting to Excel of the DataTable changed with the new column should be done AFTER the add of the column and this code that updates it
In this code the opening of the connection and the creation of the command is done before entering the loop over your rows. The parameterized query holds the new values extracted from your ROWS not from your column names and instead of a more expensive ExecuteReader, just use an ExecuteScalar. If the record is found the ExecuteScalar just returns the UserID instead of a full reader.
The issue was in my CreateExcelFile() method. I inherited the app I'm modifying and assumed the method dynamically read the data in the DataTable and built the spreadsheet. In reality, it was searching the DataTable for specific values and ignored everything else.
2 lines of code later, I'm done.

Getting Primary key values (auto number ) VB

I have a database on Access and I want to insert into 2 tables
ReportReq
req_sysino
I want to get the last value of primary key (auto numbered) and insert it into req_sysino
, I am stuck with this code and I dont know how to proccess
Private Function InsertSysInvToDB(intSysInv As Integer) As Integer
Dim strSQLStatement As String = String.Empty
Dim intNoAffectedRows As Integer = 0
Dim con As New OleDb.OleDbConnection("PROVIDER = Microsoft.ace.OLEDB.12.0; Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb")
Dim cmd As OleDb.OleDbCommand
Dim reqnum As String = "Select ##REQ_NUM from ReportReq"
strSQLStatement = "INSERT INTO req_sysino (Req_num, sysinvo_ID)" +
" VALUES (" & reqnum & "','" & intSysInv & ")"
cmd = New OleDb.OleDbCommand(strSQLStatement, con)
cmd.Connection.Open()
intNoAffectedRows = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return intNoAffectedRows
End Function
this is my insert code that should generate autonumber
Dim dbProvider = "PROVIDER = Microsoft.ace.OLEDB.12.0;"
Dim dbSource = " Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb"
Dim sql = "INSERT INTO ReportReq (Emp_EmpID, Req_Date,Req_expecDate,Req_repnum, Req_name, Req_Descrip, Req_columns, Req_Filtes, Req_Prompts)" +
"VALUES (#reqNUM,#reqName,#reqDescrip,#reqcolumns,#reqfilters,#reqprompts)"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text)
cmd.Parameters.AddWithValue("#reqDate", DateTime.Today)
cmd.Parameters.AddWithValue("#reqExpecDate", DateTime.Parse(txtbxExpecDate.Text).ToShortDateString())
cmd.Parameters.AddWithValue("#reqNUM", txtRep_NUM.Text)
cmd.Parameters.AddWithValue("#reqName", txtRep_Name.Text)
cmd.Parameters.AddWithValue("#reqDescrip", txtbxRep_Desc.Text)
cmd.Parameters.AddWithValue("#reqcolumns", txtbxColReq.Text)
cmd.Parameters.AddWithValue("#reqfilters", txtbxFilReq.Text)
cmd.Parameters.AddWithValue("#reqprompts", txtbxPromReq.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Immediately after you ExecuteNonQuery() your INSERT INTO ReportReq ... statement you need to run a
SELECT ##IDENTITY
query and retrieve its result, like this
cmd.ExecuteNonQuery() ' your existing statement to run INSERT INTO ReportReq
cmd.CommandText = "SELECT ##IDENTITY"
Dim newAutoNumberValue As Integer = cmd.ExecuteScalar()

Syntax error (comma) in query expression, header with commas

I am trying to check if value from label1 exist in dbf file column named : "NALOG,C,8". Header in DBF file I can not change, 'cause it represents column's format and field size. But with that I get this error : "Syntax error (comma) in query expression "NALOG,C,8 = #NAL"
Here is complete code :
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "NALOG,C,8"
'Dim SQLstr As String = "SELECT * FROM " & DBF_File
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV;User ID=Admin;Password="
'cmd = New OleDbCommand("SELECT * FROM " & DBF_File)
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE " & ColName & " = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", Label1.Text)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST" & TextBox1.Text
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
end using
Thanks.
If you have a column that is named this:
Dim ColName As String = "NALOG,C,8"
Then I would change it too this:
Dim ColName As String = "[NALOG,C,8]"
Use this instead:
Dim ColName As String = "NALOG"

Load SQL Statement for Dataset From SqlServer

I have a code that will fill the dataset for my crystal report which was written down as follows:
Dim str1 As String = "SELECT * FROM farm_loan WHERE id = '" & txtAgreement.Text & "'"
Dim str2 As String = "SELECT * FROM cd_farmers WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str3 As String = "SELECT * FROM cd_Address WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str4 As String = "SELECT * FROM cd_loan_charges WHERE loanid = '" & txtAgreement.Text & "'"
Dim ad1 As SqlDataAdapter = New SqlDataAdapter(str1, Conn)
Dim ad2 As SqlDataAdapter = New SqlDataAdapter(str2, Conn)
Dim ad3 As SqlDataAdapter = New SqlDataAdapter(str3, Conn)
Dim ad4 As SqlDataAdapter = New SqlDataAdapter(str4, Conn)
Dim LDPSDataSet As DataSet = New DataSet()
ad1.Fill(LDPSDataSet, "farm_loan")
ad2.Fill(LDPSDataSet, "cd_farmers")
ad3.Fill(LDPSDataSet, "cd_Address")
ad4.Fill(LDPSDataSet, "cd_loan_charges")
The above code works fine. What I am trying to do is to store the sql statement in one table called tblDataSet and load the same from sql server. Here are my code.
cmd = New SqlCommand("SELECT * FROM tblDataSet WHERE Flag = 'Y'", Conn)
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim ad As SqlDataAdapter
If reader.HasRows Then
Do While reader.Read()
MySql = reader(1).ToString
Dim table As String = reader(2).ToString
Dim comm As SqlCommand = New SqlCommand(MySql)
comm.Connection = Conn
comm.CommandType = CommandType.Text
comm.Parameters.Add("#AgreementID", SqlDbType.Int).Value=txtAgreement.Text
comm.Parameters.Add("#CustomerID", SqlDbType.Int).Value = txtCustID.Text
Dim ad As SqlDataAdapter = New SqlDataAdapter
For Each tbl As DataTable In LDPSDataSet.Tables()
If tbl.TableName = table Then
ad.SelectCommand = comm
End If
Exit For
ad.Update(tbl)
Next
Loop
End If
I have not encountered any error but no value is fetch to the crystal report.
My code in to fetch data to crystal report is show below.
With mReport
repOptions = .PrintOptions
With repOptions
.PaperOrientation = rptOrientation
.PaperSize = rptSize
.PrinterName = printer
End With
.Load(rptPath, OpenReportMethod.OpenReportByDefault)
.SetDataSource(LDPSDataSet)
'.Refresh()
.PrintToPrinter(1, True, 0, 0)
End With
Please help me identify the problem with my code.
Thanks in advance.