Taking one value from a table - vb.net

sorry if this has been asked before but I everything I found has not helped.
I'm looking to set a value from a table to the text property of a label. This is what I have so far:
In a separate class with the connection string "conn" -
(SQL Region)
Public Const SELECT_1 As String = "SELECT TOP 1 * FROM [TableTimes]
WHERE [timeID] = #PKey"
(Methods Region)
Public Shared Function returnOneRow(PrimaryKey As Integer) As TableTimes
Dim returnRow As New TableTimes(0)
Dim conn As New SqlConnection
conn.connectionstring = Conn.getConnectionString
Dim command As New SqlCommand
command.connection = conn
command.CommandType = CommandType.Text
command.CommandText = SQL.SELECT_1
command.Parameters.AddWithValue("#PKey", PrimaryKey)
Try
conn.Open()
Dim dR As IDataReader = command.ExecuteReader
If dR.Read() Then
returnRow.timeID = PK
If Not IsDBNull(dR(Fields.linkID)) Then returnRow.linkID = dR(Fields.linkID)
If Not IsDBNull(dR(Fields.dateTime)) Then returnRow.dateTime = dR(Fields.dateTime)
End If
Catch ex As Exception
Console.WriteLine(Err.Description)
End Try
Return returnRow
End Function
And then back in the main form I am trying to set the dateTime to a label based on what primary key (timeID) I enter as a parameter. This is the closest I can think of:
label.Text = (Tables.TableTimes.returnOneRow(1).dateTime).ToString
I know the output should be "2016-02-04 10:00:00" for the row with the timeID of 1 based on my table data, but instead it returns "0001-01-01 12:00:00" no matter what parameter I enter.
I would prefer to not change my method or sql statement and just change how I call the function in the main form if that's possible.
Thank you!

Related

Select max value in MS Access database

I need to select the max value in my row column. When I hit line
(FindCurrentTimeCard = Val(myreader("Row"))
I get an error:
System.IndexOutOfRangeException
Code:
Public Function FindCurrentTimeCard() As Integer
Dim myconnection As OleDbConnection = New OleDbConnection
Dim query As String = "Select MAX(Row) from Table2"
Dim dbsource As String =("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=S:\Docs\PRODUCTION\Shop Manager\Shop_Manager\Shop_Manager\Database2.accdb;")
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
Try
conn.Open()
Dim myreader As OleDbDataReader = cmd.ExecuteReader()
myreader.Read()
FindCurrentTimeCard = Val(myreader("Row"))
conn.Close()
Catch ex As OleDbException
MessageBox.Show("Error Pull Data from Table2")
FindCurrentTimeCard = 1
End Try
End Function
Table2
The issue is that when you evaluate an aggregate function (or indeed, any expression performing some operation on a field or fields), the result of such evaluation will be assigned an alias (such as Expr1000) unless an alias is otherwise stated.
Hence, when you evaluate the SQL statement:
select max(table2.row) from table2
MS Access will return the result assigned to an alias such as Expr1000:
Hence, the SQL statement does not output a column named Row, causing your code to fail when attempting to retrieve the value of such column:
FindCurrentTimeCard = Val(myreader("Row"))
Instead, you should specify an alias to which you may refer in your code, e.g.:
select max(table2.row) as maxofrow from table2
With your function then returning the value associated with such column:
FindCurrentTimeCard = Val(myreader("maxofrow"))
Comments and explanations in-line
Public Function FindCurrentTimeCard() As Integer
Dim CurrentTimeCard As Integer
'The Using block ensures that your database objects are closed and disposed
'even it there is an error
'Pass the connection string directly to the connection constructor
Using myconnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=S:\Docs\PRODUCTION\Shop Manager\Shop_Manager\Shop_Manager\Database2.accdb;")
Dim query As String = "Select MAX(Row) from Table2"
Using cmd As New OleDbCommand(query, myconnection)
Try
myconnection.Open()
'since you are only retrieving a single value
'you can used .ExecuteScalar which gets the value
'in the first row, first column
CurrentTimeCard = CInt(cmd.ExecuteScalar)
Catch ex As OleDbException
MessageBox.Show("Error Pull Data from Table2")
End Try
End Using
End Using
'vb.net uses the Return statement to return the value of the function
Return CurrentTimeCard
End Function

How can I read a specific column in a database?

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

Check if a table is empty on SQLite

I'm trying to adapt to VB.NET the code of the most voted answer from this post:
Sqlite Check if Table is Empty
Original code is
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM table";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//leave
else
//populate table
My code looks like ('Only to have a message on the screen I will fill the If - Else code later')
Using conn As New SQLiteConnection("Data Source=myDataBase.sqlite;Version=3;foreign keys=true")
Try
conn.Open()
Dim emptyUserTable = "SELECT COUNT(*) FROM usersTable"
Dim cmdIsEmpty As SQLiteCommand = New SQLiteCommand(emptyUserTable, conn)
Try
Dim Answer As Integer
Answer = cmdIsEmpty.ExecuteNonQuery()
MsgBox(Answer)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Using
But the "Answer" is allways -1, with empty table or not.
I donĀ“t know how to use getWritableDataBase because I get a
getWritableDatabase is not a member of SQLiteConnection
The same with rawQuery.
How can I check if usersTable is empty or not on VB.NET?
I've abstracted your code a little so it can be used for any table:
Private Function IsTableEmpty(tblName As String) As Boolean
Dim sql = String.Format("SELECT COUNT(*) FROM {0}", tblName)
Using conn As New SQLiteConnection(LiteConnStr)
Using cmd As New SQLiteCommand(sql, conn)
conn.Open()
Dim rows = Convert.ToInt32(cmd.ExecuteScalar())
Return rows = 0
End Using
End Using
End Function
Usage:
If IsTableEmpty("usersTable") Then
Console.Beep()
End If
Notes
The command object should be disposed when you are done with it, so it is used on a Using block.
There is not need to copy your connection string everywhere. You can define it once as a form/class level variable and reuse it everywhere
ExecuteScalar() gets the count back, then it is tested for 0 rows

VB: SQL Query return result to textbox

In short, I am working on a program that will add/edit entries to an SQL database.
One of the features for this program is that it, if given the account ID number, will look up the name under that account with that given ID. This is what I am having trouble with.
General Format:
Objective: SQL Query that will return string to textbox
AcctID => field in table with account number
AcctName => field in table with account name
txtbx_accountName => textbox I need the name returned to
NOTE:
This is all nested in a generic Try-Catch statement with error
handling.
This is all inside a Click event handler for a button.
This is all done in Visual Studio 2015
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand
myConn.ConnectionString = ""
myConn.Open() ' Open the connection
myCmd = myConn.CreateCommand()
' Build the query with the account number as paramter
myCmd.CommandText = "SELECT AcctName FROM DataSetTable WHERE (AcctID = #incomingAcctID)"
' Add the parameter so the SqlCommand can build the final query
myCmd.Parameters.Add(New SqlParameter("#incomingAcctID", (CInt(txtbx_accountNum.Text))))
' run the query and obtain a reader to get the results
Dim reader As SqlDataReader = myCmd.ExecuteReader()
' check if there are results
If (reader.Read()) Then
' populate the values of the controls
txtbx_accountName.Text = reader(0)
End If
' Close all connections
myCmd.Dispose()
myConn.Close() ' Close connection
myConn.Dispose()
i am not pro but i do like this,sorry if this not helped you:
if your Stored procedure is created to add and edit than write this and call it where you want to add:
private sub NAME(ByVAL Parameter1 name as integer,
ByVAL Parameter2 name as string,
ByVAL Parameter3 name as boolean)
Dim strConn As String = ConfigurationManager.ConnectionStrings("databaseXYZ").ConnectionString
Dim myConn As New SqlConnection(strConn)
Dim myCmd As SqlCommand
try
myConn.Open()
sqlCommand = New SqlCommand("PRCEDURE_NAME", myConn )
sqlCommand.CommandType = CommandType.StoredProcedure
dim param as new System.Data.SqlClient.SqlParameter
param.parameterName="#send_parameter1"
param.Direction = ParameterDirection.Input
param.Value = send_parameter1
dim param1 as new System.Data.SqlClient.SqlParameter
param1.parameterName="#send_parameter2"
param1.Direction = ParameterDirection.Input
param1.Value = send_parameter2
sqlCommand.Parameters.Add(Param)
sqlCommand.Parameters.Add(Param1)
sqlCommand.ExecuteNonQuery()
catch ex as exception
throw
End Try
myConn.Close()
myConn = Nothing
end sub
I'm a dummy!!!
Here is the solution, for all interested parties.
Click Event Handler (w/ nested Try-Catch):
txtbx_accountName.Text = DataSetTableAdapter.SearchNameQuery(CInt(txtbx_accountNum.Text)).ToString
SearchNameQuery:
SELECT AcctName FROM DataSetTable WHERE AcctID = #incomingAcctID
More notes on this:
- The dataset is already included in the project

How to refresh form after selecting value from combobox

I would like to know if it is possible to refresh the current windows form I am at after selecting another value from the combo box in order to display the details of that item onto several other textboxes?
So my table looks like
table name : program
program_id program_name program_desc
1 T1 desc1
This is the code i am using atm
Dim connection As New SqlClient.SqlConnection
connection.ConnectionString = "pathway"
Dim dr As SqlDataReader
Dim prognamedesc As String
Dim filetypetxt As String
Dim prognamecombo As String
Dim filetypecombo1 As String
Dim command As New SqlCommand
Dim querycommand As New SqlCommand
connection.Open()
'THIS SECTION LOADS DATA FROM THE TABLES'
Try
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "select program_name,filetype from program order by program_name; select * from filetype"
querycommand.Connection = connection
querycommand.CommandType = CommandType.Text
querycommand.CommandText = "select program_name,program_desc , filetype from program where program_name like" & FiletypeComboBox1.SelectedItem & ""
dr = command.ExecuteReader
While dr.Read()
prognamecombo = dr(0)
Program_nameComboBox.Items.Add(prognamecombo)
End While
dr.NextResult()
While dr.Read()
filetypecombo1 = dr(0)
FiletypeComboBox1.Items.Add(filetypecombo1)
FiletypeComboBox1.SelectedItem = filetypecombo1
End While
dr.NextResult()
While dr.Read()
filetypetxt = dr(0)
FiletypeLabel1.Text = filetypetxt
End While
dr.NextResult()
While dr.Read()
prognamedesc = dr(0)
Program_descTextBox.Text = prognamedesc
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
connection.Close()
I was wondering if this is doable using the current code?
To implement this you have to do two things, First put all your code inside a method and call it something like RefreshForm()
public void RefreshForm()
{
// your code and binding goes here
}
The second step is by using selected index changed event over combobox you just call the method that includes all your binding code.