Try
conn = New SqlConnection(strcon)
conn.Open()
Dim str As String = "select * from MYTABLE where Year >='#" & Txtfromyear_reprt.Text & "#' and Year <='#" & Txttoyear_reprt.Text & "#'"
da = New SqlDataAdapter(str, conn)
Dim ds As New DataSet
da.Fill(ds, "MYTABLE")
DgvReport.DataSource = ds.Tables("MYTABLE")
da.Dispose()
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
I'm working with my school project but I've encountered a problem in which I can't solve. I wrote this code in my search button but when I click it at runtime, no data is displayed in my datagrid.
What I want is when I click it I want to display all the data from mytable to the Datagrid view using two textboxes. I have two textboxes, txtfromyear and txttoyear and a database column Year with a datatype nvarchar(50).
Please help me, thank you in advance.
Don't use string concatenation to build your sql queries, NEVER!
You are open for sql injection, there is no excuse for it. Instead use sql parameters:
Dim dateFrom as Date
Dim dateTo as Date
Dim validFromDate = Date.TryParse(Txtfromyear_reprt.Text.Trim(), dateFrom)
Dim validToDate = Date.TryParse(Txttoyear_reprt.Text.Trim(), dateTo)
Now exit this method with a meaningful message if the user didn't provide valid dates. You can check validFromDate and validToDate which are booleans. The rest of the code is executed If validFromDate AndAlso validToDate:
Dim str As String = "select * from MYTABLE where Year >= #fromyear and Year <= #toyear"
da = New SqlDataAdapter(str, conn)
da.SelectCommand.Parameters.Add("#fromyear", SqlDbType.DateTime).Value = dateFrom
da.SelectCommand.Parameters.Add("#toyear", SqlDbType.DateTime).Value = dateTo
' now you can use da.Fill(ds, "MYTABLE") safely
I just saw you use varchar to store datetimes. Why? Fix it in the database.
Related
I hava a Table named DTR_Table it has 8 columns in it namely:
EmployeeID,Date,MorningTime-In,MorningTime-Out,AfternoonTime-In,AfternoonTime-Out,UnderTime,Time-Rendered.I want to read the column "AfternoonTime-In".
Following is my code. It reads my "AfternoonTime-In" field, but it keeps on displaying "Has Rows" even if there is nothing in that column.
How can I fix this?
Connect = New SqlConnection(ConnectionString)
Connect.Open()
Dim Query1 As String = "Select [AfternoonTime-Out] From Table_DTR Where Date = #Date and EmployeeID = #EmpID "
Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
cmd1.Parameters.AddWithValue("#Date", DTRform.datetoday.Text)
cmd1.Parameters.AddWithValue("#EmpID", DTRform.DTRempID.Text)
Using Reader As SqlDataReader = cmd1.ExecuteReader()
If Reader.HasRows Then
MsgBox("Has rows")
Reader.Close()
Else
MsgBox("empty")
End If
End Using`
After returning the DataReader you need to start reading from it if you want to extract values from your query.
Dim dt = Convert.ToDateTime(DTRform.datetoday.Text)
Dim id = Convert.ToInt32(DTRform.DTRempID.Text)
Using Connect = New SqlConnection(ConnectionString)
Connect.Open()
Dim Query1 As String = "Select [AfternoonTime-Out] From Table_DTR
Where Date = #Date and EmployeeID = #EmpID"
Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = dt
cmd1.Parameters.Add("#EmpID", SqlDbType.Int).Value = id
Using Reader As SqlDataReader = cmd1.ExecuteReader()
While Reader.Read()
MessageBox.Show(Reader("AfternoonTime-Out").ToString())
Loop
End Using
End Using
Note that I have changed the AddWithValue with a more precise Add specifying the parameter type. Otherwise, your code will be in the hand of whatever conversion rules the database engine decides to use to transform the string passed to AddWithValue to a DateTime.
It is quite common for this conversion to produce invalid values especially with dates
I am currently coding in VB.net using windows form applications and an sql server for my tables. I am creating an order form with two comboboxes, one for the type of material to be ordered and one for a name. There is also a submit button at the bottom to run the SQL "Insert Into" code. The material combobox is filled with a column of material types from an SQL table called "tbl.channel". Each material type under that column has a part number, ID, and bundle size associated with that row. I want ALL of the information associated with that material type to write into a new table that records all the orders, with the user only selecting the material type from a combobox. How can I use a "Select From" sql code to pull the associated information with that material type to be written into a new table that tracks all the material ordered?
Try
Dim connectionstring As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataTable
Dim i As Integer = 0
Dim sql As String = Nothing
connectionstring = "DATA SOURCE = BNSigma\Core ; integrated security = true"
sql = "Select Channel, [Bundle Size], ID from Production.dbo.tblchannel"
connection = New SqlConnection(connstring)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("INSERT INTO Production.dbo.tbl (Channel, OrderedBy, Date1, BundleSize, ID) Values (#Channel, #Orderedby, #getdate(), #BundleSize, #ID)", conn1)
With comm1.Parameters
.AddWithValue("#Channel", CBChannel.SelectedValue)
.AddWithValue("#OrderedBy", CBName.SelectedValue)
.AddWithValue("#BundleSize", CBChannel.SelectedValue)
.AddWithValue("#ID", CBChannel.SelectedValue)
End With
End Using
End Using
Catch ex As Exception
MsgBox("Unable to make SQL connection")
MsgBox(ex.ToString)
End Try
I'm not certain I understand your goal, but are you looking to just do this?
INSERT Production.dbo.tbl (Channel, OrderedBy, Date1, BundleSize, ID)
SELECT Channel, #Orderedby, getdate(), BundleSize, ID
FROM tbl.channel
WHERE ID = #ID
I am pretty well convinced though that you should only be writing the channel.ID to the orders table -- do you have a compelling reason to write the extra values?
SQL lets you use a SELECT query to populate the values for an INSERT statement. Something like this:
Public Sub PopulateOrder(ByVal MaterialID As Integer, ByVal SalesName As String)
Dim sql As String = "INSERT INTO Production.dbo.tbl (Channel, OrderedBy, Date1, BundleSize, ID) SELECT Channel, #SalesName, current_timestamp, [Bundle Size], ID from Production.dbo.tblchannel WHERE ID = #MaterialID"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'Better to declare a specific database type than let .AddWithValue() try to infer one for you
cmd.Parameters.Add("#SalesName", SqlDbType.NVarChar, 50).Value = SalesName
cmd.Parameters.Add("#MaterialID", SqlDbtype.Int).Value = MaterialID
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Call it like with code similar to this:
PopulateOrder(CBChannel.SelectedValue, CBName.SelectedValue)
But for what it's worth, it's almost always a bad idea to duplicate this information across tables.
I have this code
Dim conex As SqlConnection = New SqlConnection(conxst)
Dim caixa As Integer = ComboBox1.SelectedItem
Dim verdat As Date = DateTimePicker1.Text
Dim verdat1 As Date = "05/07/2012"
conex.Open()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New SqlDataAdapter("select codigo,data,horario from alteraca where data = '" & verdat1 & "' ", conex)
da.Fill(dt)
this code work when verdat1 is in the format "mm/dd/yyyy" , how i convert the date from mine datetimepicker (dd/mm/yyyy) to the format "mm/dd/yyyy" to place in the statment??? Thanks.
You shouldn't use string representation of a value when you already have binary representation.
Dim dt As New DataTable
Using conex As New SqlConnection(conxst)
conex.Open()
Using cmd As New SqlCommand("select codigo, data, horario from alteraca where data = #data", conex)
cmd.Parameters.AddWithValue("#data", DateTimePicker1.Value)
Using da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
End Using
End Using
With
verdat1.ToString("MM/dd/yyyy")
You can select how the date is converted to a string.
Also, you can set the dateTimePicker Custom Format as you wish :
dateTimePicker1.Format = DateTimePickerFormat.Custom
dateTimePicker1.CustomFormat = "MM/dd/yyyy"
In sql query
-use to_date to convert String to date
-and to char for reverse
In your case
select codigo,data,horario from alteraca where data = to_date('" & verdat1 & "','dd/mm/yyyy') ", conex
here 'dd/mm/yyyy' is format of your variable...
Actually, a better (and safer way) to do the query is to use Parameters and Using statements. The Using statement automatically closes the connection, commands and adapter.
Dim caixa As Integer = ComboBox1.SelectedItem
Dim verdat As Date = DateTimePicker1.Text
Dim verdat1 As Date = "05/07/2012"
Dim ds As New DataSet
Dim dt As New DataTable
Using conex as New SQLConnection(conxst)
conex.Open()
Using cmdex as New SQLCommand("select codigo,data,horario from alteraca where data = #DATE " , conxst)
cmdex.Parameters.AddWithValue("#DATE",verdat1)
Using da As New SqlDataAdapter(cmdex)
da.Fill(dt)
End Using
End Using
End Using
You can convert the date like this:
verdat1.ToString("MM/dd/yyyy")
you can use DateTimePicker1.value. It is easily solve
i need to select some records from table Tr_cashbook between two date. the date field is newdt in which i need to compare data and the records should be shown in crystal report named rptCash2. the newdt field has datetime property. here is the code on the command button
bdcon.Open()
Dim QueryString As String
QueryString = "Select * from Tr_Cashbook where (Cast(newdt as date)>= " & DateTimePicker1.Value.ToString("yyyy-MM-dd") & ") and (Cast(newdt as date) <= " & DateTimePicker2.Value.ToString("yyyy-MM-dd") & ")"
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(QueryString, bdcon)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
rptCash2.Load()
rptCash2.SetDataSource(ds)
CrystalReportViewer1.ReportSource = rptCash2
bdcon.Close()
but this is not working
when i press the command button it gives error as operand type clash: date is incompatible with int. i am not able to find out where i go wrong . help me with this..
Use parameters instead of hard-coded sql string.
Your parameterized query shoud be:
QueryString = "Select * from Tr_Cashbook where newdt>=#date1 and
newdt<= #date2"
Dim Cmd as new SqlCommand(QueryString,bdcon)
Cmd.Parameters.Add("#date1",SqlDbType.Date).Value=DateTimePicker1.Value
Cmd.Parameters.Add("#date2",SqlDbType.Date).Value=DateTimePicker2.Value
Dim Adapter As SqlDataAdapter = New SqlDataAdapter(Cmd)
Dim ds As DataSet = New DataSet()
Adapter.Fill(ds, "Tr_Cashbook")
You may use BETWEEN AND syntax:
QueryString = "Select * from Tr_Cashbook where newdate BETWEEN #date1 AND #date2"
before a little time , I used a code to get the dates between 2 dates from the database (column with dates dd/mm/yy) , I think it works nice first time , the code is :
Dim b As New Date
Dim a As Integer
a = Val(tx2.Text)
b = System.DateTime.Today
b = b.AddDays(-a)
MsgBox(b)
Conn.Open()
SQLstr = " Select * from tb where lastvstart BETWEEN #01/01/1800# AND #" & b & "#"
Dim DataAdapter1 As New OleDbDataAdapter(SQLstr, Conn)
DataSet1.Clear()
DataAdapter1.Fill(DataSet1, "Tb")
Conn.Close()
as you see , the code let the user to insert a number and minus it form the date of today , then calculates the date that I want , after that I use BETWEEN Clause to get all dates between them
But now , this code gets some data and overpasses others , I mean some of the dates is between the tow dates but the code never get it , why that happens ?
If you look at the generated SQL string, does it contain the date that you expect? I would assume that the database requires it to follow a specific format (either dd/MM/yyyy or MM/dd/yyyy given the hard coded date in the query). Could it be that your day and month switch places when the string version of the date is created and inserted into your SQL query?
As a side note, I would strongly recommend against concatenating SQL queries together like that. If possible, use parameterized queries instead. That could possibly also remove some type conversion issues.
Update
Here is an example of using a parameterized query over OLE DB to an Access database:
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""C:\path\file.mdb""")
Using cmd As New OleDbCommand("select * from tb where lastvstart BETWEEN ? AND ?", connection)
Dim param As OleDbParameter
' add first date '
param = New OleDbParameter()
param.DbType = DbType.Date
param.Value = New DateTime(1800, 1, 1)
cmd.Parameters.Add(param)
'add second date '
param = New OleDbParameter()
param.DbType = DbType.Date
param.Value = DateTime.Today.AddDays(-a)
cmd.Parameters.Add(param)
cmd.Parameters.Add(New OleDbParameter())
connection.Open()
Using adapter As New OleDbDataAdapter(cmd)
Using ds As New DataSet()
adapter.Fill(ds)
Console.WriteLine(ds.Tables(0).Rows.Count)
End Using ' DataSet '
End Using ' OleDbDataAdapter '
End Using ' OleDbCommand '
End Using ' OleDbConnection '
Can you not change the Sqlstr to
SQLstr = " Select * from tb where lastvstart <= '" & b.ToString("dd MMM yyyy") & "'";
EDIT, change based on DB
Use this string and check if it works
SQLstr = " Select * from tb where lastvstart <= #" & b.ToString("dd MMM yyyy") & "#";