While dataReader.Read() not executing - vb.net

The code executes everything but the While dataReader.Read() loop and I have no idea why. No errors are coming up, it just doesn't actually read the data with the data reader. Many thanks for any help received.
Private Sub BtnFind_Click(sender As Object, e As EventArgs) Handles BtnFind.Click
Dim cmd As OleDbCommand
Dim myConnection As OleDbConnection
Dim text As String = txtTeacherID.Text
Dim dataReader As OleDbDataReader
Try
'selects the information from the row where the column has the teacher ID
myConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\My Documents\database.accdb")
myConnection.Open()
cmd = New OleDbCommand("SELECT * FROM [TMessages] WHERE TeacherID = '" & text & "'", myConnection)
dataReader = cmd.ExecuteReader
While dataReader.Read()
lstItems.Items.Add(dataReader(0))
lstItems.Items.Add(dataReader(0))
lstItems.Items.Add(dataReader(0))
MsgBox("reading")
End While
Catch
MsgBox("Error occured")
End Try
dataReader.Close()
myConnection.Close()
End Sub

As pointed in my comment, you are only reading the same value 3 times
lstItems.Items.Add(dataReader(0))
And the read value may be in blank, try to use your reader to read all the values recieved in the dataReader thought a loop and check all the values.
for i = 0 to dataReader.FieldCount

Related

Oledb No Value Given for one or more required parameters VB.NET

I can anyone tell me whats wrong with my code? I am a complete novice here and this is the first time I have tried writing something in quite a while,
The below code should be updating two fields in an access database
Private Sub TestButton_Click(sender As Object, e As EventArgs) Handles TestButton.Click
'connects application to database
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DatabasePath\database.accdb"
Dim SqlString As String = "update SaintStaff set [StaffHours]=[#CAHours],[RecordedTime]=[#Time] where [StaffName] = " & Label2.Text & ""
'updates record in SaintStaff table.
Using conn As New OleDbConnection(ConnString)
conn.Open()
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("[#CAHours]", Label6.Text)
cmd.Parameters.AddWithValue("[#Time]", Label10.Text)
cmd.ExecuteNonQuery()
End Using
conn.Close()
End Using
End Sub
I am getting the following error
System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
and its highlighting the cmd text on each line, I cant tell what I am doing wrong, can anyone help?
Thank you
This Question was answered by MatSnow and olivier-jacot-descombes in the comments, the correct code looks as follows
Private Sub TestButton_Click(sender As Object, e As EventArgs) Handles TestButton.Click
'connects application to database
Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\DatabasePath\Database.accdb"
Dim SqlString As String = "update SaintStaff set StaffHours = #CAHours, RecordedTime = #Time where StaffName = #staffname "
'updates record in SaintStaff table.
Using conn As New OleDbConnection(ConnString)
conn.Open()
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#CAHours", OleDbType.VarChar).Value = Label6.Text
cmd.Parameters.Add("#Time", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#Staffname", OleDbType.VarChar).Value = Label2.Text
cmd.ExecuteNonQuery()
End Using
conn.Close()
End Using
End Sub

count of rows in MS access database in vb.net

Does anyone know what is wrong?
I am trying to count number of rows in MS access Database.
Here is code which I tried:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New OleDbConnection
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb")
conn.Open()
Dim strsql As String
strsql = "Select count(*) from TABLA" '" select Panel from PANELS where ID"
Dim cmd As New OleDbCommand(strsql, conn)
Dim myreader As OleDbDataReader
myreader = cmd.ExecuteReader
myreader.Read()
PanelsInDatabase = myreader.Item(strsql)
Label1.Text = PanelsInDatabase
conn.Close()
For i As Integer = 0 To PanelsInDatabase - 1
CreatePanels()
CreateDeleteButton(_PanelName)
CreateLabels(_PanelName)
CreateLabel2(_PanelName)
Next
End Sub
if I start code, I get an error:
System.IndexOutOFRangeException
I have separated you user interface code from your database code. Of course, I don't know what CreatePanels is doing or where _PanelName is coming from. In your UI code you call the GetTABLACount function which returns as Integer.
In the database code use Using...End Using blocks for the connection and command so they are properly disposed even if there is an error.
Since you are only retrieving a single piece of data, you can use .ExecuteScalar which returns the first column of the first row of the result set As Object. Use CInt to get the Integer.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim count = GetTABLACount()
Label1.Text = count.ToString
For i As Integer = 0 To count - 1
CreatePanels()
CreateDeleteButton(_PanelName)
CreateLabels(_PanelName)
CreateLabel2(_PanelName)
Next
End Sub
Private Function GetTABLACount() As Integer
Dim dbCount As Integer
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"),
cmd As New OleDbCommand("Select count(*) from TABLA", conn)
conn.Open()
dbCount = CInt(cmd.ExecuteScalar)
End Using
Return dbCount
End Function
Use ExecuteScalar when you are selecting a single value
Dim connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Dim sql = "select count(*) from tabla"
Using cmd As New OleDbCommand(sql, New OleDbConnection(connStr))
cmd.Connection.Open()
Dim ct = CInt(cmd.ExecuteScalar())
End Using

How to feed results of SQL statement into a GridView, not the SQL statement itself?

This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form

Reading OleDb records into TextBox using ComboBox VB.NET

I'm new to programming. What i'm trying to accomplish is to fill in 9 textboxes in VB.NET, reading access table TblKlanten, using a combobox (CbbNaamfirma). I cannot get this to work for the life of me; i've been searching for 6 hours for this simple thing. Can any of you help me out? I've read numerous threads on SO.com like this and they all just won't work for me.
Code i have now:
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim Connection As New OleDb.OleDbConnection
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Application.StartupPath & "\Database.accdb.'"
Try
Connection.Open()
Dim query As String
query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ' " & CbbNaamfirma.Text & " ' "
Dim cmd As New OleDbCommand(query, Connection)
Dim Reader As OleDbDataReader = cmd.ExecuteReader
Reader = cmd.ExecuteReader
While Reader.Read
TxtAdresprev.Text = Reader.GetString("Adres")
End While
Connection.Close()
Catch ex As OleDbException
MessageBox.Show(ex.Message)
Finally
Connection.Dispose()
End Try
End Sub
Thank you in advance. Hope that code block turned out alright?
The first thing to change is the reading from the database using a parameterized query. Notice that your code cannot find anything because you add a space before and after the value of the combobox.
Then you need to start employing the using statement around the disposable objects to ensure a proper closing and disposing
Finally the GetString method from the OleDbDataReader wants a numeric index inside the returned list of fields, not the name of the field
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
Application.StartupPath & "\Database.accdb"
Dim query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ?"
Using Connection = New OleDb.OleDbConnection(cnString)
Using cmd = New OleDbCommand(query, Connection)
Try
Connection.Open()
cmd.Parameters.AddWithValue("#p1", CbbNaamfirma.Text)
Using Reader = cmd.ExecuteReader
While Reader.Read
Dim posAdres = Reader.GetOrdinal("Adres")
TxtAdresprev.Text = Reader.GetString(posAdres)
.... other text boxes for other fields here.....
End While
End Using
Catch ex As OleDbException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Also your connection string seems to be wrong. No need of quotation and that stray point after the fielname is wrong

Insert a record in sql database using vb.net datatable and datarow features

I am trying to insert a record in sql database using vb.net dataadapter, datatable, and datarow features. I use the following code but it gives me an error:
Object reference not set to an instance of an object
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=drpractice;Integrated Security=True")
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Try
cn.Open()
da.SelectCommand = New SqlCommand("SELECT * FROM [emp_tbl]", cn)
da.Fill(ds)
Dim dt As New DataTable
dt = ds.Tables("emp_tbl")
'Error in this line(Object reference not set to an instance of an object)'
Dim dr As DataRow = dt.NewRow()
dr.Item("emp_id") = TextBox1.Text.Trim
dr.Item("emp_name") = TextBox2.Text.Trim
dr.Item("salary") = TextBox3.Text.Trim
dr.Item("age") = TextBox4.Text.Trim
dr.Item("emp_group") = TextBox5.Text.Trim
dt.Rows.Add(dr)
da.Update(ds)
MsgBox("Record Successfully Inserted")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
check this out : Dim dr As DataRow = new dt.NewRow()
You have done everything good but change the following line:
da.Update(ds)
As following:
Dim ESCBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
ESCBuilder.GetUpdateCommand()
da.UpdateCommand = ESCBuilder.GetUpdateCommand()
da.Update(ds)
Based on the feedback here and elsewhere, the following code worked for me:
TestDataSet.GetChanges()
testTableAdapter.Fill(TestDataSet.log_test)
log_testDataGridView.Refresh()
What I needed to do was, create a new row, and go get the next value for the Primary Key(VARCHAR, NOT INT, because revisions got an "R" appended to the PK...not my rule...the rule of the company).
I wanted to put the refresh as close to the getting of the PK, which I had last after assigning values to the new datarow so it would get the latest Max +1.
So, I put the above code just before looking up the PK, and after assigning values to the datarow, other than PK. The code above caused the datarow to blank out. So, I put the above code just prior to the creation of the new DataRow.
For my code, this caused the code to get the latest data from the SQL table, then add the new datarow, and finally determine the last PK. Because the data used to populate the datarow is off my form, and there is no caclulations, the code runs fast enough for my needs. I suspect, if the connection to my database was slow, and/or, the number of people running the same process were substantial, I would have errors, such as duplicate PKs.
My answer to that would be to assign the datarow field values to variables, run the refresh, then assign the variables to the fields and save immediately.
Perhaps another way would be to get the new PK, then save an empty record, and then fill the record, except that enough of the fields in my table are REQUIRED so I might as well not try creating a blank record first.
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim str As String
Dim count As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New SqlConnection("server=SHREE-PC;database=Hospital;INTEGRATED SECURITY=SSPI;")
con.Open()
‘ cmd = New SqlCommand("select * from Doctor", con)
str = "insert into Doctor values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "' )"
cmd = New SqlCommand(str, con)
count = cmd.ExecuteNonQuery()
MessageBox.Show(count & " Record inserted")
con.close()
End Sub
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim str As String
Dim count As Integer
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
con = New SqlConnection("server=SHREE-PC;database=Hospital;INTEGRATED SECURITY=SSPI;")
con.Open()
cmd = New SqlCommand("select * from Patient", con)
cmd = New SqlCommand("Delete from Patient where Name ='" & TextBox1.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Address='" & TextBox2.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Dieses='" & TextBox3.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Patient_no=" & TextBox4.Text & "", con)
‘you can take any row in your program
count = cmd.ExecuteNonQuery()
MessageBox.Show("Record Deleted")
End Sub