Retrieve data from database in asp.net using vb - vb.net

Below is the code for fetching the data into textbox but its not working it shows error no data exits row/column whereas data and datafield are perfectly alright.
Please help.
Dim Connection As OleDbConnection
Connection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("/db/QardanHasana.mdb"))
Connection.Open()
Dim ejamaatregcmd As OleDbCommand
Dim ejamaatregdtrdr As OleDbDataReader
ejamaatregcmd = New OleDbCommand("SELECT ITSData.[EJamaatID], ITSData.[ITSFirstName] FROM ITSData WHERE EjamaatID= #EjamaatID", Connection)
ejamaatregcmd.Parameters.Add(New OleDbParameter("#EjamaatID", txtEjamaatID.Text))
ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.HasRows Then
txtFirstName.Text = ejamaatregdtrdr.item("ITSFirstName").ToString()
end if

A DataReader needs a call to Read to position itself on the first record retrieved
ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.HasRows Then
ejamaatregdtrdr.Read()
txtFirstName.Text = ejamaatregdtrdr.item("ITSFirstName").ToString()
End if
By the way, Read returns false if there are no rows to read, so you could remove the test for HasRows and write simply
ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.Read() Then
txtFirstName.Text = ejamaatregdtrdr.item("ITSFirstName").ToString()
End if
Another suggestion to improve your code is to start using the Using Statement
Using Connection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;....")
Using ejamaatregcmd = new OleDbCommand("SELECT ITSData.[EJamaatID], ITSData.[ITSFirstName] FROM ITSData WHERE EjamaatID= #EjamaatID", Connection)
Connection.Open()
ejamaatregcmd.Parameters.Add(New OleDbParameter("#EjamaatID", txtEjamaatID.Text))
Using ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.Read() Then
txtFirstName.Text = ejamaatregdtrdr.item("ITSFirstName").ToString()
End if
End Using
End Using
End Using
The using statement is invaluable to help you to close and dispose the disposable objects like the connection, the command and the reader. Lacking a proper dispose your code uses more memory and locks resources resulting in a more unstable application.

Before reading data from a DataReader, you need to move the row to the first row by calling the Read method. It returns true if data exist, so you don't need to check the HasRows property:
ejamaatregdtrdr = ejamaatregcmd.ExecuteReader()
If ejamaatregdtrdr.Read() Then
txtFirstName.Text = ejamaatregdtrdr.Item("ITSFirstName").ToString()
End if

I'll generally do something like the following
Function GetResult(ID As string) As String
GetResult = "No Data" 'Default Result
Dim conn As System.Data.OleDb.OleDbConnection = *NewConnectionObject*
Dim comm As System.Data.OleDb.OleDbCommand = *NewCommmandObject*
comm.Parameter.AddWithValue("#Parametername",ID)
Using reader As System.Data.OleDb.OleDbDataReader = comm.ExecuteReader()
If reader.HasRows Then
'Reader has data, so iterate through it
GetResult = ""
while reader.read
GetResult += reader("FirstName")
End While
Else
'Either Do Nothing - Default Result will show
'Throw New System.Exception("Empty Data") 'Try Catch Statement have overhead.. so it's not a popular methodology
'Or Log Something..
End If
End Using
If conn.state = connection.open Then
conn.close
End
End Function

Related

Having the ExecuteNonQuery : connection property has not been initialized

I'm trying to delete an entry from my database. But when the ExecuteNonQuery has to do it's job it can't find the enabled connection and give me this error :
System.InvalidOperationException :'ExecuteNonQuery : connection property has not been initialized'
Here is what I did :
Dim delete As New OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim dt As DataTable
initConnectionDtb(pathDtb)
openConnection()
If TextBox2.Text <> "" Then
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
MsgBox("USER HAS BEEN DELETED")
Else
MsgBox("ERROR")
End If
I could check if it was properly connected to the Database thanks to connectionName.State
I also enterily rewrote the connetion to the database in the function but ExecuteNonQuery still couldn't connect even though the connection was opened
I saw that i'm not the only one on this website but none of the previous answers have helped me.
#Filburt pointed out, how are you assigning your connection to your command object. Here is an example :
Using connection As OleDbConnection = New OleDbConnection(connectionString)
connection.Open()
Dim command As OleDbCommand = New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()
End Using
In your code, you need to assign the connection object to your command object. We can't see what code you have in initConnectionDtb(pathDtb) or openConnection()
To adapt this to your code:
delete.Connection = <<your connection object here>>
delete.CommandText = "delete FROM USERS WHERE NAME = '" & TextBox2.Text & "'"
delete.CommandType = CommandType.Text
delete.ExecuteNonQuery()
Another note: look into parameterizing your query strings instead of hand stringing the values. This will prevent issues with TextBox2.Text having a value like O'Toole which will cause a syntax error as well as SQL Injection.
Here's what i used to initialize my connection :
Public Function initConnectionDtb(ByVal path As String) As Boolean
initConnectionDtb = True
Connection = New OleDbConnection
Try
Connection.ConnectionString = "provider=microsoft.jet.oledb.4.0;" & "data source= " & path & ";"
Catch ex As Exception
Return False
End Try
End Function
Public Function openConnection() As Boolean
openConnection = True
Try
Connection.Open()
MsgBox(Connection.State) 'to test if my connection really openned in my previous post
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub closeConnection()
If Not IsNothing(Connection) Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
MsgBox(Connection.State)
Connection.Dispose()
Connection = Nothing
End If
End Sub
So far it worked for everything i tried (adding someone to the database for exemple)

Reading from a database and using an if statement

The program currently reads from the database, but what I am trying to do is try to get the program to read from the database and if the field is empty then output "TBC" and if not then it will show the grade. I'm unsure of how to check what dr.Read is and use an if statement with it.
Sub GradeResult()
Dim dr As OleDbDataReader
Dim cm As New OleDbCommand
Dim cn As New OleDbConnection
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=login.accdb"
cn.Open()
cm.CommandText = "SELECT ArGrade FROM loginDetails WHERE UserName = '" & username & "'"
cm.Connection = cn
dr = cm.ExecuteReader
dr.Read()
Label6.Text = dr.Item("ArGrade")
End Sub
Instead of using an if statement, when the user registers, the program writes TBC into the field.
dr is an instance of the OleDbDataReader class, and Read is one public method of this class. You need to call it in order to start reading the results after a query is executed against the database.
From the OleDbDataReader.Read documentation page:
Advances the OleDbDataReader to the next record.
You need to call it at least once, to get some results.
Returns
Boolean
true if there are more rows; otherwise, false.
Use it to check if you have any results at all or more results as one.
The default position of the OleDbDataReader is before the first record. Therefore, you must call Read to start accessing any data.
In your case you can check if there is any result like this:
Label6.Text = "TBC" ' standard value is no value found
if dr.Read() then ' DB contains any rows
dim arGrade = dr.Item("ArGrage")
if not IsDbNull(arGrade) then ' and the ArGrade has a value
Label6.Text = arGrade
end if
end if
And don't forget to close the reader with dr.Close.

Failed to read when no data is present

i have this code,,its work (kind of).
Dim connString As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
Dim conn As New SqlConnection(connString)
conn.Open()
Dim comm As New SqlCommand("SELECT username, Password,type FROM users WHERE username='" & TextBox1.Text & "' AND Password='" & TextBox2.Text & "'", conn)
Dim reader As SqlDataReader
reader = comm.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("username and password are correct")
Form2.Show()
Form2.Label1.Text = Me.TextBox1.Text
Form2.Label2.Text = reader(2).ToString
ElseIf count > 1 Then
MessageBox.Show("username and password are duplicated")
Else
MessageBox.Show("username and password are wrong")
End If
im getting error with this line:
Form2.Label2.Text = reader(2).ToString
and error is "Invalid attempt to read when no data is present"
why its says "no data"
i have all data in database?
can someone help me to correct this code?
thank you ..
You should not be using a loop at all. There should be no way that you can get more than one record so what use would a loop be? You should be using an If statement and that's all:
If reader.Read() Then
'There was a match and you can get the data from reader here.
Else
'There was no match.
End If
If it's possible to have two records with the same username then there's something wrong with your database design and your app. That column should be unique and your app should be testing for an existing record when someone tries to register.
A SqlDataReader is a forward only data read element. The error is occurring because you're calling the reader's READ function twice; once as true to increment to 1, and a second time to get a false to fall out of the while statement. Since you're no longer in the WHILE statement, the reader had to have read the end of the result set, thus there is no data for you to read.
Consider the changed code below:
Dim connString As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString
Dim count As Integer = 0
Dim userType as string = ""
Using conn As New SqlConnection(connString)
conn.Open()
Using Comm as SqlCommand = conn.CreateCommand
comm.commandText = "SELECT username, Password, type FROM Users WHERE username = #UserName AND Password = #Pwd; "
comm.parameters.AddWithValue("#Username", TextBox1.Text)
comm.parameters.AddWithValue("#Password", Textbox2.text)
Dim reader As SqlDataReader
reader = comm.ExecuteReader
If reader IsNot Nothing Then
If reader.HasRows() Then
While reader.read
count = count + 1
If Not reader.IsDbNull(2) Then userType = reader(2).ToString
End While
End If
If Not reader.IsClosed Then reader.close
reader = Nothing
End If
End Using
End Using
If count = 1 Then
MessageBox.Show("username and password are correct")
Form2.Show()
Form2.Label1.Text = Me.TextBox1.Text
Form2.Label2.Text = userType
ElseIf count > 1 Then
MessageBox.Show("username and password are duplicated")
Else
MessageBox.Show("username and password are wrong")
End If
First off, SQLParameters are your friend. Learn them. They are the single easiest way to fight against SQL Injection when using the SqlClient classes.
Secondly, notice that I'm doing the actual retrieval of the data from the reader inside the WHILE loop. This ensures that there's actual data for me to read.
Third, notice the USING statements on the SqlConnection and SqlCommand objects. This helps with garbage collection, and has a couple of other benefits as well.
Finally, notice the checks I'm doing on the SqlDataReader before I ever attempt to access it. Things like that would prevent from another error appearing if you did not return any results.

Loop through action

I am new to visual basic, however I need to loop through rows in a data table and use the values to in a test script, the script is as follows -
Public Function TestMain(ByVal args() As Object) As Object
StartApp(URL)
' HTML Browser '
Browser_HtmlBrowser(Document_HomePage(),DEFAULT_FLAGS).Maximize()
Button_AddNewProfilesubmit().Click()
'here is where the rows would be read and the loop would start'
Text_Ctl00MainContentProfileNa().Click(AtPoint(6, 13))
Browser_HtmlBrowser(Document_Http1921685526UserCon(), DEFAULT_FLAGS).InputChars("dataBase_Row_Value")
Table_HtmlTable_1().Click(AtCell( _
AtRow(AtIndex(0)), _
AtColumn(AtIndex(1))))
'here is where the loop would end after all rows had been read'
Return Nothing
End Function
I have an idea to achieve this, first doing a database connection, then create the loop -
Dim pName As String
Dim datas As DataSet
Dim datar As DataRow
Dim oledat As SqlDataAdapter
oledat = New SqlDataAdapter("SELECT COLUMN FROM DATABASE",ConnectionString)
oledat.Fill(datas)
For Each datar In datas.Tables(0).Rows
pName = datar.Item("PROFILENAME")
Text_Ctl00MainContentProfileNa().Click(AtPoint(6, 13))
Browser_HtmlBrowser(Document_Http1921685526UserCon(), DEFAULT_FLAGS).InputChars(pName)
Table_HtmlTable_1().Click(AtCell( _
AtRow(AtIndex(0)), _
AtColumn(AtIndex(1))))
Next
However this is breaking, even though there are no errors in Visual Studio, there is only the warning that datas is used before it is assigned the values. Where am I going wrong?
I believe you must initialize a new dataset before working with it. Example:
Dim ds As DataSet = New DataSet()
Dim connection As OleDb.OleDbConnection
Dim command As OleDb.OleDbCommand
Dim adapter As New OleDb.OleDbDataAdapter
Dim connString As String = "my Connection string stuff;"
connection = New OleDb.OleDbConnection(connString)
Try
'open the connection
If connection.State = ConnectionState.Open Then
Else
connection.Open()
End If
'fill each data table
command = New OleDb.OleDbCommand(selectOne, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "someTableName")
Catch ex As OleDb.OleDbException
'error, do something
Finally
'close everything down
adapter.Dispose()
If (Not command Is Nothing) Then
command.Dispose()
End If
connection.Close()
End Try
This example uses OLEDB but should be comparable to what you are doing. Once you fill it, you should be able to iterate over the tables. But, first, check to make sure you have a dataset created first:
If (ds IsNot Nothing) Then
'do for statement here
End If
If this does not work, let me know.

Better way to print out rows from a datatable in vb.net

I am new to vb.net and I am trying to query a database and print out the records in the row to the console window. I got it to work, but I have a feeling that there is a more concise way to do this. One thing that I am sure is wrong is that I had to convert the dataset to a datatable to be able to retrieve the values. Is that correct? Could you take a look at the code below (especially the for loop) and let me know what I can improve upon?
Thanks!
Module Module1
Sub Main()
Dim constring As String = "Data Source=C:\Users\test\Desktop\MyDatabase1.sdf"
Dim conn As New SqlCeConnection(constring)
Dim cmd As New SqlCeCommand("SELECT * FROM ACCOUNT")
Dim adapter As New SqlCeDataAdapter
Dim ds As New DataSet()
Try
conn.Open()
cmd.Connection = conn
adapter.SelectCommand = cmd
adapter.Fill(ds, "testds")
cmd.Dispose()
adapter.Dispose()
conn.Close()
Dim dt As DataTable = ds.Tables.Item("testds")
Dim row As DataRow
Dim count As Integer = dt.Columns.Count()
For Each row In dt.Rows
Dim i As Integer = 0
While i <= count - 1
Console.Write(row(i))
i += 1
End While
Console.WriteLine(Environment.NewLine())
Next
Catch ex As Exception
Console.WriteLine("There was an error")
Console.WriteLine(ex)
End Try
Console.ReadLine()
End Sub
End Module
Here is how I would rewrite this for a few reasons:
1) You should always use Using statements with disposable objects to ensure they are correctly cleaned up. You had a good start with the dispose commands, but this way is safer.
2) It is more efficient to use ExecuteReader than loading everything into a dataset.
3) Your try/catch statement should include object creation as well as execution.
Finally, in response to your question about datasets and datatables, that code was absolutely correct: a dataset consists of zero or more datatables, so you were just extracting the existing datatable from the dataset.
Try
Dim constring As String = "Data Source=C:\Users\test\Desktop\MyDatabase1.sdf"
Using conn As New SqlCeConnection(constring)
conn.Open()
Using cmd As New SqlCeCommand("SELECT * FROM ACCOUNT", conn)
Dim reader As SqlCeDataReader
reader = cmd.ExecuteReader()
Do While reader.Read
For i As Integer = 0 To reader.FieldCount - 1
Console.Write(reader.GetString(i))
Next
Console.WriteLine(Environment.NewLine())
Loop
End Using
End Using
Catch ex As Exception
Console.WriteLine("There was an error")
Console.WriteLine(ex)
End Try
Console.ReadLine()
End Sub
One last note: since you are just printing to the console, it doesn't matter as much, but whenever you deal with a lot of strings, especially those that are to be concatenated, you should always consider using System.Text.StringBuilder.
Here is an example rewrite of the loop that prints to the console using stringbuilder (builds the string in memory, then dumps it to the console; I have also added the field name for good measure):
Dim sbOutput As New System.Text.StringBuilder(500)
For i As Integer = 0 To reader.FieldCount - 1
If sbOutput.Length <> 0 Then
sbOutput.Append("; ")
End If
sbOutput.Append(reader.GetName(i)).Append("=").Append(reader.GetString(i))
Next
sbOutput.AppendLine()
Console.Write(sbOutput.ToString)