How to display database connection status in VB 2010 - database

I'm developing Point of sales system. and i want to display database connection status for the users. Im using MS Access 2013 database and Visual Studio 2010 (VB). I created module for this project as follows,
Imports System.Data.OleDb
Module ModConVar
Public sql As String
Public cmd As OleDbCommand
Public dr As OleDbDataReader
Public conn As OleDbConnection
Public connStr As String = System.Environment.CurrentDirectory.ToString & "\NCS_POS_DB.accdb"
Public Sub ConnDB()
Try
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & connStr & "")
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Module
And I have a label named lblDBStatus in main MDI form, I tried with followin code, but it dosent work.
If conn.State = ConnectionState.Open Then
lblDBStatus.Text = "CONECTED"
End If
any suggestions please ??

You're displaying "CONNECTED" only when the connection state is open. Otherwise your label will not show anything
Try this and make sure that the connection is open:
If conn.State = ConnectionState.Open Then
lblDBStatus.Text = "CONNECTED"
Else
lblDBStatus.Text = "DISCONNECTED"
End If

The OleDbConnection exposes a StateChanged event.
So you can track the state like this:
Public Sub ConnDB()
Using connection As New OleDbConnection("...")
AddHandler connection.StateChange, AddressOf Me.OnConnectionStateChange
Try
connection.Open()
'Do stuff..
Catch ex As Exception
Throw ex
Finally
RemoveHandler connection.StateChange, AddressOf Me.OnConnectionStateChange
End Try
End Using
End Sub
Private Sub OnConnectionStateChange(sender As Object, e As StateChangeEventArgs)
MessageBox.Show(e.CurrentState.ToString())
End Sub

Related

VB.NET insert data via form

I am trying to insert data to database, but getting error as ExecuteNonQuery: Connection property has not been initialized.
Everything seems ok with the connection.
Imports System.Data.SqlClient
Public Class crud1
Private Sub Add_btn_Click(sender As Object, e As EventArgs) Handles Add_btn.Click
Try
Dim conn_ As New SqlConnection("Data Source=DESKTOP-VVM5A31;Initial Catalog=temp;Integrated Security=True")
conn_.Open()
Dim command As New SqlCommand("INSERT INTO STUDENT (student_name, student_age) VALUES (#NAME, #AGE)")
command.Parameters.AddWithValue("#NAME", TXT_NAME.Text)
command.Parameters.AddWithValue("#AGE", Convert.ToInt32(TXT_AGE.Text))
command.ExecuteNonQuery()
MsgBox("Record saved.", MsgBoxStyle.Information)
conn_.Close()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
Please see the image for the connection property.
You are right taking into account that the command needs the connection open, before execute the command, and you are doing right.
But you are not telling to the command which is the connection to be used.
An easy way to do it would be something like this, before execute the command:
command.Connection = conn_

DataTable not updating Database with DataAdapter (VB.NET)

*NOTE: I deleted my previous question "Update Database from DataTable and DataAdapter" in place of this one. I have updated the wording and code to be what I am currently testing.
I am trying to update a database with info from a WinForm. I had no issues when using a “normal” SQL update command written by hand (parameters set to the text box values,) but I am trying to clean up and reduce my code and I thought I would bind the controls to a DataTable and use a DataAdapter's update command to achieve the same thing.
I have tried to get various combinations of setting parameters and update commands to work, but the Database is not getting updated from the new DataTable values. I have stepped through the code with each change and can see that the DataTable is getting the new textbox values, but those updates aren’t going to the Database. (This is seen when the Fill_Date block runs and selects all new data from the database.)
Things I’ve tried: Letting the binding get the new values vs. setting the parameters manually. Using the command builder to build the update command, using the .UpdateCommand.ExecuteNonQuery(), command and of course a straight.Update(DataTable) command.
Below is the code that I am using. I am hoping someone can tell me what it is I am doing wrong/missing, or what is the correct path to take. Is there a "best practice" or a better way to do this?
Public Class frmDATA
Dim dt_Test As New DataTable
Dim da_Test As New SqlDataAdapter
Dim SQLcmd As SqlCommand
Private Sub frmDemog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BuildSQL()
Fill_Data()
BindControls()
End Sub
Private Sub frmDemog_Closed(sender As Object, e As EventArgs) Handles Me.Closed
If Not IsNothing(dt_Test) Then dt_Test.Dispose()
If Not IsNothing(da_Test) Then da_Test.Dispose()
If Not IsNothing(SQLcmd) Then SQLcmd.Dispose()
Me.Dispose()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Update_Me()
End Sub
Private Sub BindControls()
txtLName.DataBindings.Add("Text", dt_Test, "Last_Name")
txtFName.DataBindings.Add("Text", dt_Test, "First_Name")
txtAKA.DataBindings.Add("Text", dt_Test, "AKA")
End Sub
Public Sub Update_Me(RefreshSearch As Boolean, RefreshView As Boolean)
Try
Dim testID As Integer = frmTest.dgvSearch.CurrentRow.Cells(0).Value
da_Test.UpdateCommand.Parameters("#ID").Value = testID
da_Test.Update(dt_Test)
Fill_Data()
Catch SqlExceptionErr As SqlException
MsgBox(SqlExceptionErr.Message, vbCritical, "Error")
Catch ex As Exception
MsgBox(ex.Message, vbCritical, "Error")
End Try
End Sub
Public Sub Fill_Data()
Try
dt_Test.Clear()
da_Test.SelectCommand.Parameters("#ID").Value = testID
da_Test.Fill(dt_Test)
Catch SqlExceptionErr As SqlException
MsgBox(SqlExceptionErr.Message, vbCritical, "Error")
Catch ex As Exception
MsgBox(ex.Message, vbCritical, "Error")
End Try
End Sub
Private Sub BuildSQL()
'** Build Selection Query
SQLcmd = New SqlCommand(String.Join(Environment.NewLine,
"SELECT ",
"data_Test.[Last_Name], ",
"data_Test.[First_Name], ",
"data_Test1.[Last_Name] + ', ' + data_Test1.[First_Name] as [AKA] ",
"FROM [DB].data_Test ",
"LEFT JOIN [DB].data_Test as data_Test1 ",
"ON data_Test.[ID] = data_Test1.[AKA_Demog_ID] ",
"WHERE data_Test.[ID]=#ID"
), Vars.sqlConnDB)
SQLcmd.Parameters.Add("#ID", SqlDbType.Int)
da_Test.SelectCommand = SQLcmd
'** Build Update Query
SQLcmd = New SqlCommand(String.Join(Environment.NewLine,
"UPDATE [DB].data_Test SET ",
"[Last_Name] = #LName,",
"[First_Name] = #FName",
"WHERE [ID] = #ID"
), Vars.sqlConnDB)
With SQLcmd.Parameters
.Add("#LName", SqlDbType.NVarChar, 255, "Last_Name") 'Required
.Add("#FName", SqlDbType.NVarChar, 255, "First_Name") 'Required
.Add("#ID", SqlDbType.Int, 0, "ID")
End With
da_Test.UpdateCommand = SQLcmd
End Sub
End Class

vb.net crystal report is asking for database login and password but logon failed

I'm new in making crystal reports and I'm done creating my crystal report but when running my program it asks for my logon information but after I log in, it says that
logon failed
I tried to look in other questions here in the site but I was not able to find an answer. My Visual Studio is 2013 Ultimate and my sql is sql-server 2014 express.
Here's my code:
Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim show As String = String.Empty
show &= "select * from fruit_stock "
show &= "where date_received=#daterec"
Using conn As New SqlConnection("server=WIN10;database=fruit_storage;user=fruit_admin;password=admin;")
Using cmd As New SqlCommand
With cmd
.Connection = conn
.CommandType = CommandType.Text
.CommandText = show
.Parameters.AddWithValue("#daterec", TextBox1.Text)
End With
Try
conn.Open()
Dim da As New SqlDataAdapter
Dim ds As New DataSet
da.SelectCommand = cmd
da.Fill(ds, "fruit_stock")
Dim report As New CrystalReport1
CrystalReportViewer1.ReportSource = report
CrystalReportViewer1.Refresh()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
End Sub
End Class
Dim report As New CrystalDecisions.CrystalReports.Engine.ReportDocument
report.Load("<physical filename of your report>")
report.SetDataSource(ds.Tables("fruit_stock"))
<your_crystal_report_viewer_in_your_form>.ReportSource = report
if you are using an embedded report
Dim report As New <Name of your embedded crystal report>
report.SetDataSource(ds.Tables("fruit_stock"))
<your_crystal_report_viewer_in_your_form>.ReportSource = report

VB.Net Open image from database to picturebox

I'm trying to open an image from my database to a picture box but I just don't how to do it.
I've searched for some answers and I am not familiar with the codes for I am beginner only.
The only codes that I researched about are for connecting the database to the system:
Imports System.Data.OleDb
Module Module1
Public acsconn As New OleDbConnection
Public acsdr As OleDbDataReader
Public acsda As New OleDbDataAdapter
Public acscmd As New OleDbCommand
Public strsql As String
Public acsds As New DataSet
Public Sub connect()
Try
acsconn.ConnectionString = "provider=microsoft.jet.oledb.4.0; data source=|datadirectory|\database1.mdb;"
acsconn.Open()
If acsconn.State = ConnectionState.Open Then
MsgBox("Connected")
Else
MsgBox("Error")
End If
Catch ex As Exception
End Try
End Sub
End Module
I do not know what is next. BTW, those codes - I used it for saving the image to the database.
I think this is the sort of thing you are looking for:
Private Sub HandleRequest(context as HttpContext)
Dim SqlCnn As SqlConnection = Nothing, sql As String
Dim emp_id As Integer
emp_id = Int32.Parse(context.Request.QueryString("id"))
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub

An attempt to attach an auto-named database for file failed in Vb.Net

I am Trying to connect database for first time , and I am getting this error :
An attempt to attach an auto-named database for file VBTestDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
and getting error on
myconnect.Open()
Heres my code :
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=VBTestDB.mdf;Integrated Security=True;User Instance=True;"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO Card (CardNo,Name) VALUES (#cardno,#name)"
myconnect.Open()
Try
mycommand.Parameters.Add("#cardno", SqlDbType.Int).Value = TextBox1.Text
mycommand.Parameters.Add("#name", SqlDbType.NVarChar).Value = TextBox2.Text
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
MsgBox(ex.Message)
End Try
myconnect.Close()
End Sub
I am able to solve my problem.
I just change my connection string to :
myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=VBTestDB;Integrated Security=True;User Id=sa;Password=welcome1"
and it works fine.
Thanks

Resources