I am getting this error "There is no row at position 0." vb.net as the frontend and sql server 2008 as the db - sql

This is my code, I m getting error "There is no row at position 0."
Sub loadservicetype()
Dim str As String = "SELECT servicename FROM tbl_activity WHERE activity= '" & CmbActivity.Text & "' "
Dim dt As New DataTable
Dim sdr As New SqlDataAdapter(str, connection)
sdr.Fill(dt)
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End Sub

First thing is Always Use SQL Parameter to AVOID SQL injection
Like this
Dim commandText As String = "SELECT servicename FROM tbl_activity WHERE activity=#ID"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
command.Parameters.Add("#ID", SqlDbType.Int).Value = ID
Try
connection.Open()
Dim rowsAffected As String = command.ExecuteNonQuery()
Catch ex As Exception
throw
End Try
End Using
MSDN SOURCE
Your DataTable is Doesn't Return any rows which You Are Trying to Access
If dt IsNot Nothing Then
If dt.Row.Count>0 Then
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End If
End If

Related

How to use cmd.parameters.add("#ID") SQL, VB.NET

Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM"
Using command As New SqlCommand(sql, conn)
Using adapter As New SqlDataAdapter(command)
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
'command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
adapter.Fill(dt)
TextBox1.Text = dt(0)(0)
End Using
End Using
End Using
This code working properly asper my expectation. When I use "where ID=#ID" in sqlcommand It's showing error: 'Input string was not in a correct format.'
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
Using adapter As New SqlDataAdapter(command)
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
adapter.Fill(dt)
TextBox1.Text = dt(0)(0)
End Using
End Using
End Using
In this code I'm getting error. Could someone help me how to declare "#ID". Thank you..
Please check the error description.
enter image description here
That's maybe because you are trying to add parameters using the statement of the adapter.
Try this:
Dim idValue As Int = Convert.ToInt32(TextBox1.Text)
Dim dt As DataTable = New DataTable()
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
command.Parameters.Add("#ID", SqlDbType.Int).Value = idValue
Using adapter As New SqlDataAdapter(command)
adapter.Fill(dt)
End Using
End Using
End Using
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
TextBox1.Text = dt(0)(0)
If you want to change the way you using to parse string to int:
Dim idValue As Int = Integer.Parse(TextBox1.Text)
Dim dt As DataTable = New DataTable()
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
command.Parameters.AddWithValue("ID", idValue)
Using adapter As New SqlDataAdapter(command)
adapter.Fill(dt)
End Using
End Using
End Using
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
TextBox1.Text = dt(0)(0)
it looks like in your broken code you need/want to have multiple "id" or more than one value. You can do this, but you ALSO then have to add the parameters to the source sql string.
You can't just add, or have multiple #ID values for the one "#ID".
If you want more than one ID value in the same sql query, then you have to add multiple "#id1" then "#id2" and so on to the sql text for this to work.
So, if you have ONE "#ID" then fine.
However, if you have say id 2, 134, 222?
Then you would have to add each parmater to the sql string.
You can do it this way:
dim strSQL as string = "SELECT * FROM MyTable"
dim strWhere as string = ""
dim cmdSQL as New Sqlcommand("", new Sqlconneciton("con string here")
' add first #id
strWhere = "#ID1"
cmd.SQL.Paramters.Add("#ID1", SqlDbType.Int).Value = 124
' add 2nd #!id
strWhere &= ",#ID2"
cmd.SQL.Paramaters.Add("#ID2", SqlDbType.Int).Value = 456
' and so on and so on
cmdSQL.CommandText = strSQL & " WHERE ID IN (" & strWhere & ")"
dim rstData as new DataTable()
cmdSQL.conneciton.Open()
rstData.Load(cmdSQL.ExectuteReader())
Note VERY interesting that you can create the sql command object, and are 100% free to add as many new parameters as possible to the cmdSQL object, and EVEN do so without having the sql command/text set for the sql command object.
However, you EVENTUALLY will have to setup/provide/have the sql shoved into that command object. So, build up the multiple "#id1, #id2" etc., and then shove that whole correct sql string into the cmdSQL object, and it will work.
However, as noted, you are 100% free to add as many parameters to the cmdSQL object, and even do so without having the SQL made/set/created for the cmdSQL object. They thus can be created 100% independent of the existing sql string/text (or better said lack of that sql string during the parameter adding process).

Syntax Error! >_<

Guy's Cant seem to find my error in VB.Net ! my codes are all right ! but the function still won't save on the database cause of Syntax error in my Insert into statement ! Please help me ! :D!
This is my Code!:D!
Dim Transaction As OleDb.OleDbTransaction = Nothing
Dim Connection As OleDb.OleDbConnection = Nothing
Try
Connection = New OleDb.OleDbConnection(My.Settings.POS_CanteenConnectionString)
Connection.Open()
Transaction = Connection.BeginTransaction
Dim SQL As String = "Insert into Recipt (ReciptDate,ReciptTotal)Values(:0,:1)"
Dim CMD1 As New OleDb.OleDbCommand
CMD1.Connection = Connection
CMD1.Transaction = Transaction
CMD1.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", Now.Date)
CMD1.Parameters.AddWithValue(":1", TextBox4.Text)
CMD1.ExecuteNonQuery()
CMD1.Dispose()
SQL = "Select Max(ReciptID) As MAXID from Recipt"
Dim CMD2 As New OleDb.OleDbCommand
CMD2.Connection = Connection
CMD2.Transaction = Transaction
CMD2.CommandText = SQL
Dim ReciptID As Long = CMD2.ExecuteScalar()
CMD2.Dispose()
Dim I As Integer
For I = 0 To DGV3.Rows.Count - 1
Dim BarCode As String = DGV3.Rows(I).Cells(0).Value
Dim BuyPrice As Decimal = DGV3.Rows(I).Cells(2).Value
Dim SellPrice As Decimal = DGV3.Rows(I).Cells(3).Value
Dim ItemCount As Integer = DGV3.Rows(I).Cells(4).Value
Dim CMD3 As New OleDb.OleDbCommand
SQL = "Insert to ReciptDetails" & _
"(ReciptID,BarCode,ItemCount,ItemBuyPrice,ItemSellPrice)" & _
"Values" & _
"(:0 ,:1 ,:2 ,:3 ,:4 )"
CMD3.Connection = Connection
CMD3.Transaction = Transaction
CMD3.CommandText = SQL
CMD3.Parameters.AddWithValue(":0", ReciptID)
CMD3.Parameters.AddWithValue(":1", BarCode)
CMD3.Parameters.AddWithValue(":2", BuyPrice)
CMD3.Parameters.AddWithValue(":3", ItemCount)
CMD3.Parameters.AddWithValue(":4", SellPrice)
CMD3.ExecuteNonQuery()
CMD3.Dispose()
Next
Transaction.Commit()
Transaction.Dispose()
Connection.Close()
Connection.Dispose()
DGV3.Rows.Clear()
TextBox4.Text = ""
Catch ex As Exception
If Transaction IsNot Nothing Then
Transaction.Rollback()
End If
If Connection IsNot Nothing Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
End If
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "ERROR")
End Try
Firstly, I don't think sp parameters are called by : prefix, you should use # instead. you'll therefore need to replace the .AddWithValue (everywhere) by;
CMD1.Parameters.AddWithValue("#0", Now.Date)
CMD1.Parameters.AddWithValue("#1", TextBox4.Text)
Secondly, I think the Insert syntax isn't right, you've place TO instead of INTO and space missing. Try this;
SQL = "Insert into ReciptDetails " & _
"(ReciptID, BarCode, ItemCount, ItemBuyPrice, ItemSellPrice)" & _
" Values (#0, #1, #2, #3, #4)"

I get only column headers using sqldatareader and datagridview

I have a SQL Server 2008 express with a database and a table and using VB 2010 express.
I am trying to read from that table with sqldatareader, but I only one row in the datagridview with the column headers, no row with data.
What am I doing wrong? (I'm a newbe).
The connection string is :
Data Source=xxxxxxxxxx\SQLEXPRESS;Initial Catalog=Masteca_Inventory;Integrated Security=True
Dim searchStr As String = ""
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sqlStr As String
Public bindingSource1 As New BindingSource()
connetionString = My.Settings.SQLconnSTR
sqlStr = "SELECT * FROM Piese WHERE " & searchStr 'searchStr is OK I fill it elsewhere
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sqlStr, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
Using sqlReader
Dim dTable As New DataTable
dTable.Load(sqlReader)
bindingSource1.DataSource = dTable
End Using
SearchReport.DataGridView1.DataSource = bindingSource1
'SearchReport is another form
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
SearchReport.Show()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
You are not reading the data as a group (you are fetching only one result).
You will need to adjust the code to use a While sqlReader.Read;
Example;
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
Try
'Do the work needed
rowResult += sqlReader(0) 'This will contain the result script
Catch ex As Exception
'Catch exception
End Try
End While
Something like that should work (I have not tested the code but the concept is the same).
PS - I strongly suggest you adjust your script to add a Where clause and / or the columns needed (Select * is not a "good practice")
Hope this helps.

OleDbException 'unspecified error'

So, i get the OleDBException "unspecified error" whenever the function below hits the dataAdapter.SelectCommand = dbcommand line.
I have tried adding dbcommand.connection.close() and dbcommand.connection.dispose() but neither fixed the problem.
I assume that this error would happen every time i try to connect with the DB but this is just the first function that does so in my code, so this is where the error is first occuring.
I have read online that MySQL will eventually clear out old connections after a while, if this is true, then i should just have to wait..but i dont want to keep waiting for nothing to happen.
Function GetOrders(ByVal _numberrecords As Long) As DataTable
Dim TaxConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ConfigurationManager.AppSettings("Database")
Dim dbConnection As OleDbConnection = New OleDbConnection(TaxConnStr)
Try
'Code to get orders in call status. Sort oldest to newest
' dbConnection.Open()
Dim queryString As String
queryString = "SELECT TOP " & _numberrecords & " Orders.Control_Number, Orders.State, Orders.County, Orders.Status, Orders.ZipCode, Orders.OrderNumber, Orders.Client, Orders.Department "
queryString += "FROM Orders "
queryString += "WHERE(((Orders.Status) = 'Tax Cert Call' Or (Orders.Status) = 'Online')) "
queryString += "ORDER BY Orders.Date_Received;"
Dim dbCommand As OleDbCommand = New OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
'dbCommand.Connection.Close()
'dbCommand.Connection.Dispose()
'dbCommand.Dispose()
Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As DataSet = New DataSet
dataAdapter.Fill(dataSet)
If dataSet.Tables(0).Rows.Count >= 1 Then
GetOrders = dataSet.Tables(0)
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
myLogger.Log(ex.Message)
Finally
dbConnection.Close()
dbConnection.Dispose()
End Try
End Function

oledbexception 'unspecified error' when filling dataset

So, i get the OleDBException "unspecified error" whenever the function below hits the dataAdapter.Fill(dataset) line.
I have tried adding dbcommand.connection.close() and dbcommand.connection.dispose() but neither fixed the problem.
I assume that this error would happen every time i try to connect with the DB but this is just the first function that does so in my code, so this is where the error is first occuring.
I have read online that MySQL will eventually clear out old connections after a while, if this is true, then i should just have to wait..but i dont want to keep waiting for nothing to happen.
Function GetOrders(ByVal _numberrecords As Long) As DataTable
Dim TaxConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ConfigurationManager.AppSettings("Database")
Dim dbConnection As OleDbConnection = New OleDbConnection(TaxConnStr)
Try
'Code to get orders in call status. Sort oldest to newest
' dbConnection.Open()
Dim queryString As String
queryString = "SELECT TOP " & _numberrecords & " Orders.Control_Number, Orders.State, Orders.County, Orders.Status, Orders.ZipCode, Orders.OrderNumber, Orders.Client, Orders.Department "
queryString += "FROM Orders "
queryString += "WHERE(((Orders.Status) = 'Tax Cert Call' Or (Orders.Status) = 'Online')) "
queryString += "ORDER BY Orders.Date_Received;"
Dim dbCommand As OleDbCommand = New OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
'dbCommand.Connection.Close()
'dbCommand.Connection.Dispose()
'dbCommand.Dispose()
Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As DataSet = New DataSet
dataAdapter.Fill(dataSet)
If dataSet.Tables(0).Rows.Count >= 1 Then
GetOrders = dataSet.Tables(0)
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
myLogger.Log(ex.Message)
Finally
dbConnection.Close()
dbConnection.Dispose()
End Try
End Function
Found the problem. My Access Database was corrupted. I just remade the database and it all worked like gravy.