the connection string property has not been initialized. vb.net access. BELOW is the code - vb.net

Try
If MsgBox("SAVE THIS ACADEMIC YEAR?", vbYesNo + vbQuestion, title) = vbYes Then
cn.Open()
cm = New OleDbCommand("update [tblay] set status = 'CLOSE'", cn)
cm.ExecuteNonQuery()
cn.Close()
cn.Open()
cm = New OleDbCommand("INSERT INTO [tblay] (aycode,year1,year2,division)values(#aycode,#year1,#year2,#division)", cn)
With cm
.Parameters.AddWithValue("aycode", txtAY.Text)
.Parameters.AddWithValue("year1", txtYear1.Text)
.Parameters.AddWithValue("year2", txtYear2.Text)
.Parameters.AddWithValue("division", cboDivision.Text)
.ExecuteNonQuery()
End With
cn.Close()
MsgBox("NEW ACADEMIC YEAR HAS BEEN SUCCESSFULLY SAVED!", vbInformation, title)
With frmAY
.LoadRecords()
End With
Clear()
End If
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
This is the code to load records:
Sub LoadRecords()
Try
DataGridView1.Rows.Clear()
Dim i As Integer
cn.Open()
cm = New OleDbCommand("select * from tblay", cn)
dr = cm.ExecuteReader
While dr.Read
i += 1
DataGridView1.Rows.Add(i, dr.Item("aycode").ToString, dr.Item("year1").ToString, dr.Item("year2").ToString, dr.Item("division").ToString, dr.Item("status").ToString)
End While
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
End Sub

This might be more than you want so if so sorry.
SQLite Database (DB) CRUD function are very Boiler Plate Code. That Said I use the same process repetably.
By pacing the code in Using blocks NO need to close the DB and other functions.
I create a button for each function SAVE DELETE and UPDATE that call the function.
Here are the functions.
This code needs to be placed top level
Public connStr As String = "Data Source={0};Version=3;"
Public conn As SQLiteConnection
Here is the SAVE data NOTE the '{gv_dbName} is declared in a Module.
Private Sub InsertSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
Try
cmd.CommandText = "INSERT INTO LinkTable (ytChannelName,ytLinkAddress,ytLastVisit,ytSiteType) VALUES (#ytChannelName,#ytLinkAddress,#ytLastVisit,#ytSiteType)"
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Insert Failed")
End Try
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
Here is the DELETE.
Private Sub DeleteSiteData()
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
cmd.CommandText = "DELETE FROM LinkTable WHERE LID =" & gvID
cmd.ExecuteNonQuery()
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
And the UPDATE.
Public Sub UpdateSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;"),
cmd As New SQLiteCommand("UPDATE LinkTable SET ytChannelName = #ytChannelName, ytLinkAddress = #ytLinkAddress ,ytLastVisit = #ytLastVisit,ytSiteType = #ytSiteType WHERE LID =" & gvID, conn)
conn.Open()
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.Parameters.Add("#LID", DbType.String).Value = gvID
cmd.ExecuteNonQuery()
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub

Related

if theres no record display in datagridview then messagebox no member found

im using datagridview to display employee details and when theres no record found there will be a messagebox that there were no record found here's my code.
Dim search As String = String.Empty
search &= "select * from record "
search &= "where identification=#identification;"
Using conn As New SqlConnection("server=KENJOY_FMCD;database=humanresource;user=ayala747;password=4525422;")
Using cmd As New SqlCommand()
With cmd
.Connection = conn
.CommandType = CommandType.Text
.CommandText = search
.Parameters.AddWithValue("#identification", vsearch.Text)
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
If ds.Tables.Count >= 0 Then
DataGridView1.DataSource = ds.Tables(0)
End If
If (ds Is Nothing) Then
MsgBox("No record found!")
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
End Sub
End Class

Am new to asp.net and vb.net.,now am trying to make a gridview of a database table

now am trying to make a gridview of a database table named UploadProject.while selecting row of gridview display image in seperate image field by using imageurl At the time of compiling of following code image not displayed.an error occured..."incorect syntax near '='".Any body please help me to solve this problem
Protected Sub OnSelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
lblimageid.Text = row.Cells(0).Text
lbltitle.Text = row.Cells(1).Text
get_Address()
get_Image()
End Sub
Public Sub get_Address()
Dim qry As String
Try
cn.Open()
qry = "select (title,imageurl) from [UploadProject] where [id] = '" & lblimageid.Text & "'"
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes2.ForeColor = Drawing.Color.Red
lblmes2.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub get_Image()
Dim qry As String
Try
cn.Open()
qry = "select title,imageurl from UploadProject where id = " & lblimageid.Text
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes1.ForeColor = Drawing.Color.Red
lblmes1.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub getProjectDT()
Dim qry As String
Try
qry = "select id,title,date from UploadProject "
sda = New SqlDataAdapter(qry, cn)
ds = New DataSet
sda.Fill(ds, "UploadProject")
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
Catch ex As Exception
Finally
cn.Close()
End Try
End Sub

error 'There is already an open DataReader associated with this Command which must be closed first.'

I use below code but it gives error on sentence icount = cmd.ExecuteNonQuery
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Try always calling the Close method when you have finished using the DataReader object.
dr1.Close();
Another optionis to turn on MARS , in your connection string just add "MultipleActiveResultSets=True;"
Try this:
Try
insert data in combobox
cmd.Connection = con
cmd.CommandText = "select name from party"
dr = cmd.ExecuteReader()
cb_ms.Items.Add("---Select---")
cb_ms.SelectedIndex = 0
While dr.Read() 'get error here.'
cb_ms.Items.Add(dr("name"))
End While
dr.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
You could just close the datareader before the 2nd query, but it's better still to get this all into a single query in the first place. Moreover, you really need to close that awful sql injection issue.
Try this to fix both issues:
Dim sql As String = _
"IF NOT EXISTS
(
SELECT 1 FROM [SchoolERP].[dbo].[caste] where (caste = #caste )
)
BEGIN
INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES( #caste)
END"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'Use actual columnn type from the database here
cmd.Parameters.Add("#caste", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cn.Open()
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
End Using
Use Try.. Catch.. Finally... End Try somehing like this:
Try
cn.Open()
str = "SELECT [srno],[caste]FROM [SchoolERP].[dbo].[caste] where (caste ='" + (TextBox1.Text) + "')"
cmd = New SqlCommand(str, cn)
dr1 = cmd.ExecuteReader()
If Not dr1.HasRows Then
str = "INSERT INTO [SchoolERP].[dbo].[caste]([caste])VALUES('" + TextBox1.Text + "')"
cmd = New SqlCommand(str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
Else
MsgBox("Record Exists")
cn.Dispose()
End If
cn.Close()
Catch error As Exception
........
Finally
dr1.Close
End Try
I got Answer ... i only close connection before icount = cmd.ExecuteNonQuery this sentence and again open connection...and its works..
thanks disha..

VB.net 2010 dataset updates but access database remains same

I have tried to insert or update from my vb.net form into MS-Access database.
The dataset updates but the access database wont. Below is my code.
Try
Dim addLocation As String = "Insert into Provider (StateCode, Provider)" _
& "values ('" & ComboBox1.Text & "', '" & TextBox2.Text & "')"
Dim sqlcommand As New OleDbCommand
conn.Open()
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record added", MsgBoxStyle.Information)
refreshGrid()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Private Sub refreshGrid()
cnString = "PROVIDER = Microsoft.ace.oledb.12.0;data source =" & Application.StartupPath & "\HCHPClosedIn.accdb"
sqlQRY = "SELECT * FROM Provider"
conn = New OleDbConnection(cnString)
Try
conn.Open()
da = New OleDbDataAdapter(sqlQRY, conn)
Dim cb As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "Customers")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers"
End Try
End Sub
Its been a while but I think I recall Access is kinda picky with commit. Try this:
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
.transaction = trans
End With
Trans.Commit()

how to simplify codes

I have a next button.
theres no error i just want to simplify
Try
lblcat.Text = ds.Tables("evaluation").Rows(cat)("QuestionCategory")
txt1.Text = ds.Tables("evaluation").Rows(CurrentRow)("Question")
txt2.Text = ds.Tables("evaluation").Rows(CurrentRow + 1)("Question")
txt3.Text = ds.Tables("evaluation").Rows(CurrentRow + 2)("Question")
txt4.Text = ds.Tables("evaluation").Rows(CurrentRow + 3)("Question")
txt5.Text = ds.Tables("evaluation").Rows(CurrentRow + 4)("Question")
Catch ex As Exception
End Try
every click to the next button my category and questions change.
every click i want also to save in my database
Private Sub Save_commit()
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
'get connection string declared in the Module1.vb and assing it to conn variable
con = New OleDbConnection(Get_Constring)
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
'I just use the textbox tag property to idetify if the data is new or existing.
sSQL = "INSERT INTO evaluationresult ([Com])" & _
" VALUES (?)"
cmd.CommandText = sSQL
cmd.Parameters.AddWithValue("#FacultyID", txtresult.Text)
'cmd.Parameters.AddWithValue("#IDNumber", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Com", OleDbType.Numeric).Value
' cmd.Parameters.AddWithValue("#Know", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Teaching", OleDbType.Numeric).Value
'cmd.Parameters.Addwithvallue("#man", OleDbType.Numeric).Value()
'cmd.Parameters.AddWithValue("#ID", OleDbType.Numeric).Value
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ErrorToString)
Finally
con.Close()
End Try
End Sub
please improve