Get Difference of two dates retrieve from MS Access database using visual basic - vb.net

Dim da As New OleDb.OleDbDataAdapter("SELECT ITemID, ItemName, ItemDescription, ItemQuantity, ItemBorrowedDate, ItemReturnDate FROM BorrowedItem order by ID DESC", conn)
Dim dt As New DataTable
da.Fill(dt)
OverDueList.DataSource = dt.DefaultView
Dim ItemReturenedDate As New Date
Dim DateToday As Integer
Dim DateDiff As New Date
ItemReturenedDate = dt.Rows(0)("ItemReturnDate")
DateDiff = DateDiff(DateInterval.Day, ItemReturenedDate, DateTimePicker1.Value)`
I tried that code to generate output but my knowledge was not that good. i need help, it could be a great help if someone would notice it

And if you looking to send all rows to say a grid?
then this:
Dim strSQL As String =
"Select ITemID, ItemName, ItemDescription, ItemQuantity, ItemBorrowedDate, ItemReturnDate,
(ItemReturnDate - ItemBorroedDate) as MyDays
FROM BorrowedItem order by ID DESC"
dim dt as DataTable = MyRst(strSQL)
So, you can return MyDays for each row, and then say send the data table to a data grid view.
And I get VERY tired very fast typing over confection string and command objects, so you can use this routine (over and over).
Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using conn As New OleDbConnection(My.Settings.AccessDB)
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function

Try something like this:
Dim ItemReturenedDate As Date
Dim Days As Long
ItemReturenedDate = dt.Rows(0)("ItemReturnDate")
Days = DateTimePicker1.Value.Subtract(ItemReturenedDate).TotalDays

Related

Datagridview from mysql: Simple inventory stocks

I'm trying to create a simple inventory stock and i'm having a hard time to get the remaining stocks base on the input and output from mysql.
What I really need is to subtract the total quantity of input.quantity - output.quantity where input.material is equal to output.material and if the total.quantity is below the safety stocks the datagridview will highlight the row.
conn = New MySqlConnection
conn.ConnectionString = "server=localhost;userid=root;password=1234;database=inventory"
Dim searchquery As String = "Select input.DeliveryDate as 'Delivery Date',input.Material, (sum(input.Quantity) - sum(output.Quantity)) as 'Remaining Stocks' where rawmaterialsinput.Material = output.Material, safetystandard.safetystocks from inventory.input, inventory.output, inventory.safetystandard"
Dim commander As New MySqlCommand(searchquery, conn)
Dim adapter As New MySqlDataAdapter(commander)
inventorydata.Clear()
adapter.Fill(inventorydata)
inventoryDGV.DataSource = inventorydata
as of now this is the codes I'm trying but there's no hope. Please help
I need to have 4 column in datagridview with Delivery Date, Rawmaterials, Remaining Stocks, Safety Stocks.
conn.Open()
conn = New MySqlConnection
conn.ConnectionString = "server=localhost;userid=root;password=SOUTHEAST;database=reportingsystem"
Dim searchquery As String = "Select reportingsystem.rawmaterialswarehouseandrawmaterials.Rawmaterials as 'Raw Material', reportingsystem.rawmaterialswarehouseandrawmaterials.safetystocks as 'Safety Stocks', (select sum(reportingsystem.rawmaterialsinput.Quantity) - sum(reportingsystem.rawmaterialsoutput.Quantity) from reportingsystem.rawmaterialsinput, reportingsystem.rawmaterialsoutput where reportingsystem.rawmaterialsinput.RawMaterial = reportingsystem.rawmaterialswarehouseandrawmaterials.Rawmaterials ) as 'Remaining Stocks' from reportingsystem.rawmaterialswarehouseandrawmaterials" ' JOIN reportingsystem.rawmaterialsinput.RawMaterial ON reportingsystem.rawmaterialswarehouseandrawmaterials.Rawmaterials = reportingsystem.rawmaterialsinput.RawMaterial ORDER BY reportingsystem.rawmaterialswarehouseandrawmaterials.Rawmaterials"
Dim commander As New MySqlCommand(searchquery, conn)
Dim adapter As New MySqlDataAdapter(commander)
monitoringdata.Clear()
adapter.Fill(monitoringdata)
MonitoringDGV.DataSource = monitoringdata
conn.close()
in this code only 3 column is selected. Hope it's help

vb.net Loading Images from Access Database to DataTable?

So I have a MS Access Database with 1 table (Records) and 2 fields in it ("RecordID" (Number), which is the primary key, and "LowRes" (OLE Object) which is a low Resolution image). There are about 100 records.
I/m trying to load the Access Table into a DataTable (ID_Table) in VB.net.
Code so far:
Dim cnString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=SBS2257_ID.accdb;"
Dim theQuery As String = "SELECT [RecordID], [LowRes] FROM [Records];"
Using CN As New OleDbConnection(cnString)
Dim command As New OleDbCommand(theQuery, CN)
Using objDataAdapter = New OleDbDataAdapter(command)
Dim ID_Table As New DataTable
CN.Open()
Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
Dim picture As Image = Nothing
Using stream As New IO.MemoryStream(pictureData)
picture = Image.FromStream(stream)
objDataAdapter.Fill(ID_Table)
End Using
End Using
End Using
However the "DirectCast" command fails when I tell it to look at more then 1 field in my SQL statement with a datatype mismatch (if I just do [LowRes] it does not throw a error). However, I get stuck again when trying to apply the result to the table via the objDataAdapter, it doesnt fill the table with anything? I also notice that "picture" only contains the first image in the database.
I could put this database query in a function using "WHERE RECORDID=..." and loop it manually building the table returning "picture" each time, but Id like to avoid running a function 100 times, esp one that access a database.
Is it possible to read the whole database that contains images and just load it directly into a Datatable in one big swoop?
EDIT: So I got this to work:
Dim strConnection As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=SBS2257_ID.accdb;"
Dim strSQL As String = "SELECT [RecordID], [LowRes] FROM [Records];"
Using objConnection = New OleDbConnection(strConnection)
Using objCommand = New OleDbCommand(strSQL, objConnection)
Using objDataAdapter = New OleDbDataAdapter(objCommand)
Dim objDataTable As New DataTable("IDs")
objDataAdapter.Fill(objDataTable)
Return objDataTable
End Using
End Using
End Using
how ever when I go to view row 0, col 1 which should be the first LowRes image via a .ToString Useing this code:
Private Sub PrintValues(ByVal table As DataTable)
For Each row As DataRow In table.Rows
For Each col As DataColumn In table.Columns
MsgBox(row(col).ToString())
Next col
Next row
End Sub
It just displays "System.Byte[]". It knows its a Byte datatype, but how do I display that in a picturebox?
The ExecuteScalar() executes the query, and returns the first column of the first row in the result set returned by the query.
as your query is
Dim theQuery As String = "SELECT [RecordID], [LowRes] FROM [Records];"
the first column is RecordID which is not a Byte().
you can change your query as following:
Dim theQuery As String = "SELECT [LowRes] FROM [Records];"
or you have to use other methods to get data from the database
Dim strSql As String = "SELECT [RecordID], [LowRes] FROM [Records]"
Dim dtb As New DataTable
Using cnn As New OleDbConnection(connectionString)
cnn.Open()
Using dad As New OleDbDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using

Joining many-to-many DataTables in VB.Net

I have 2 data sources from different source types, like:
Dim connSql As String = "Data Source=sql_src;Initial Catalog=my_db;Persist Security Info=True;User ID=usr;Password=pwd;"
Dim connOle As String = "Provider=IBMDA400;Data source=src;User Id=usr;Password=pwd"
dim qrySql as String = "Select uniqueID, name From tblSql"
dim qryOle as String = "Select name, ID From tblOle"
I place them into DataTables using functions like this (mostly for reference):
Public Shared Function sqlQryDT(qry As String, conn As String) As DataTable
Dim dt As New DataTable
Dim sqlconn As New SqlClient.SqlConnection(conn)
sqlconn.Open()
Dim adapter As New SqlClient.SqlDataAdapter(qry, sqlconn)
Try
adapter.Fill(dt)
Catch ex As Exception
Finally
sqlconn.Close()
End Try
Return dt
End Function
Public Shared Function oleQryDT(qry As String, conn As String) As DataTable
Dim dt As New DataTable
Dim cn As New OleDb.OleDbConnection(conn)
Dim cmd As New OleDb.OleDbCommand("", cn)
Dim da As New OleDb.OleDbDataAdapter(cmd)
cmd.CommandText = qry
Try
cn.Open()
da.Fill(dt)
Catch ex As Exception
Finally
cn.Close()
End Try
Return dt
End Function
Dim dtSql as DataTable = sqlQryDT(qrySql, connSQL)
Dim dtOle as DataTable = oleQryDT(qryOle , connOle)
My goal is to have a DataTable consisting of uniqueID,name,ID
(Edit) If I could do an SQL query it would look like SELECT * FROM dtSql JOIN dtOle ON dtSql.name = dtOle.name
I have tried using a DataRelation by placing the tables into a DataSet and adding a relationship on name, but since names may not be unique, this fails.
I have also tried using LINQ, but that always returns IEnumerable(System.Collections.Generic) and I can't find an easy way to place the contents into a DataTable, except by iterating through every item. And, the code is messy when there are a large number of columns.
I feel like there should be a way to do this without using a For Each loop
I looked at these question, but they didn't fully help me.
How to inner join two already filled DataTables in VB.NET
Merging 2 data tables in vb.net

Select with condition from a datatable in VB.net

I want to select a certain field from a datatable in VB based on the value of another field in the same row.
In SQL, it would easily be done by writing this query:
select error_message from table_errors where error_case="condition"
How do I do this if I have my SQL table filled in a datatable in VB?
How do I select the item("error_message") in the datatable based on the item("error_Case") field?
Any help would be appreciated
You can use Linq-To-DataSet:
Dim matchingRows As IEnumerable(Of DataRow) =
From row In table
Where row.Field(Of String)("error_case") = "condition"
If you just want one column (of course that works also in one step):
Dim errorMessages As IEnumerable(Of String) =
From row In matchingRows
Select row.Field(Of String)("error_message")
For Each error In errorMessages
Console.WriteLine(error)
Next
If you expect it to be just a single row use First or Single(throws an exception if there is more than one row):
Dim error As String = errorMessages.First()
Since First throws an exception if the sequence is empty you can use FirstOrDefault:
Dim error As String = errorMessages.FirstOrDefault() ' is null/Nothing in case of an empty sequence
All in one line (note that both Linq and DataTable.Select needs to use loops):
Dim ErrMessage As String = errorTable.AsEnumerable().
Where(Function(r) r.Field(Of String)("Error_Case") = TextCase.Text).
Select(Function(r) r.Field(Of String)("Error_Message")).
FirstOrDefault()
here is a worker version of the rough code
Dim connString As String = "select error_message from table_errors where error_case='condition'"
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(connString)
conn.Open()
Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(connString, conn)
Dim dTable As DataTable = New DataTable()
Dim dAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(cmd)
dAdapter.Fill(dTable)
conn.Close()
Dim text As String
Dim dReader As DataTableReader = dTable.CreateDataReader()
While dReader.Read()
text = dReader.GetValue(0)
End While
dReader.Close()

How to populate arraylist with SQL query?

I am developing a VB.NET ASPX file. This report is currently working but now I want to add a parameter which should be an array list displaying all records from below SQL query:
" select distinct instrument_name AS instrument_name from FRUD.tblXref order by instrument_name "
But this array list displays "System.Data.Common" for all possible values from code:
Sub Main()
Dim pcSQL As String
Dim ProductList As New ArrayList()
pcSQL = " select distinct instrument_name AS instrument_name from FRUD.tblXref order by instrument_name "
Dim DBConn As SqlConnection
DBConn = New SqlConnection(ConfigurationManager.AppSettings("AMDMetricsConnectionString"))
DBConn.Open()
Dim reader As SqlDataReader
Dim DBCommand As New SqlCommand(pcSQL, DBConn)
reader = DBCommand.ExecuteReader()
dProdCodeSearch.DataSource = reader
dProdCodeSearch.DataBind()
reader.Close()
I am sure I am doing something wrong which is a really simple fix. This SQL Connection works for my data tables in this report. But this is only parameter that I set to SQL output.
You need to create a Collection that is storing the values from the database and then read those values into an array. Something like
Dim instrumentNames As New List(Of String)
While reader.Read()
instrumentNames.Add(reader.GetString("insturment_name"))
End While
dProdCodeSearch.DataSource = insturmentNames