Weird array issue.....need advice on this - arrays

I am reading data from an sql database and the connection happens but the following error occurs:
{"Index was outside the bounds of the array."}
On this line:
TextBox2.Text = TextBox2.Text & sqRdr.GetValue(22) & vbCrLf
Please help me with this as I have counted all the columns in my table and they have turned out to be exactly (22).

The column ordinal for the datareader is 0 based, so the 22nd column would be sqRdr.GetValue(21)

Your Datareader should be like below to avoid this issue in a case when you have increased/decreased the number of column in future....
DR["ColumnName"]
SqlDataReader's this[string name] looks like:
Public Overrides Default ReadOnly Property Item(name As String) As Object
Get
Return Me.GetValue(Me.GetOrdinal(name))
End Get
End Property
Below is the sample code...
Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
con.Open()
Dim cmd As New SqlCommand()
Dim expression As String = "Parameter value"
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure"
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
cmd.Connection = con
Using dr As IDataReader = cmd.ExecuteReader()
'You code like ....dr["YourColumnName"]
If dr.Read() Then
End If
End Using
End Using

Related

Error when trying to insert data from vb.net datagridview into SQL Server table

I get this error when I run the code. The records are inserted into the table, but the program stops at the error.
The parameterized query '(#EmpName varchar(8000),#USDBasic varchar(8000),#OtherUSDEarning' expects the parameter '#EmpName', which was not supplied.
Code:
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=Server\SQlExpress;Initial Catalog=CreSolDemo;User ID=sa;Password=Mkwn#011255"
cnn = New SqlConnection(connetionString)
If DataGridView1.Rows.Count > 0 Then
Dim cmd As New Data.SqlClient.SqlCommand
cmd.CommandText = " INSERT INTO TempPeriodTrans (EmpName, USDBasic, OtherUSDEarnings, ZDollarBasic, OtherZDEarnings) VALUES (#EmpName, #USDBasic, #otherUSDEarnings, #ZDollarBasic, #OtherZDEarnings) "
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar)
cmd.Parameters.Add("#USDBasic", SqlDbType.VarChar)
cmd.Parameters.Add("#OtherUSDEarnings", SqlDbType.VarChar)
cmd.Parameters.Add("#ZDollarBasic", SqlDbType.VarChar)
cmd.Parameters.Add("#OtherZDEarnings", SqlDbType.VarChar)
cmd.Connection = cnn
cnn.Open()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
cmd.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).Value
cmd.Parameters(1).Value = DataGridView1.Rows(i).Cells(1).Value
cmd.Parameters(2).Value = DataGridView1.Rows(i).Cells(2).Value
cmd.Parameters(3).Value = DataGridView1.Rows(i).Cells(3).Value
cmd.Parameters(4).Value = DataGridView1.Rows(i).Cells(4).Value
cmd.ExecuteNonQuery()
Next
cnn.Close()
End If
MsgBox("Record saved")
End Sub
There seem to be a few things here.
As a rule, any time you open a connection to your data base it should be wrapped in a Using block so that that connection gets closed and disposed before you exit that block
You have a lot of params that are being set as SqlDbType.varchar where you should probably have other types. (SqlDbType.Money in particular)
When you are working with sqlcommand, it is worth wrapping it in a using block as well and creating a new one as you need it.
There is some memory to it where it will try not to reuse parameters in subsequent queries. Instead of just changing the value of the param, throw that sqlCommand in the trash bin each time and grab a new one. This is where I believe your problem is. I moved the sqlcommand creation into your loop and declare the values in-line below.
Also, protip, avoid including your actual password in the connetion string on Stack Overflow
Dim connectionString As String = "yourConnectionString"
Using cnn As new SqlConnection(connectionString)
cnn.Open()
For Each row in DataGridView1.Rows
Using cmd As New Data.SqlClient.SqlCommand("INSERT INTO TempPeriodTrans (EmpName, USDBasic, OtherUSDEarnings, ZDollarBasic, OtherZDEarnings) Values (#EmpName, #USDBasic, #otherUSDEarnings, #ZDollarBasic, #OtherZDEarnings) ", cnn)
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar).value = row.Cells(0).Value
cmd.Parameters.Add("#USDBasic", SqlDbType.VarChar).value = row.Cells(1).Value
cmd.Parameters.Add("#OtherUSDEarnings", SqlDbType.VarChar).value = row.Cells(2).Value
cmd.Parameters.Add("#ZDollarBasic", SqlDbType.VarChar).value = row.Cells(3).Value
cmd.Parameters.Add("#OtherZDEarnings", SqlDbType.VarChar).value = row.Cells(4).Value
cmd.ExecuteNonQuery()
End using
Next
End using
MsgBox("Record Saved")
End Sub

how to insert Data into SQL Database?

In the Database, I used an assigned ProgName = varchar,MaleCuteOff = int,FemaleCutOff=int, and I'm trying to collect User input for the values, but I'm getting an Error
Conversion from string "INSERT INTO CutOff_Point((ProgN" to type
integer is not valid.
Sub save()
Dim query As String = "INSERT INTO CutOff_Point (ProgName, MaleCutOff, FemaleCutOff) VALUES (#colProg, #colMale, #colFemale)"
Using con As New SqlConnection("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True")
Using com As New SqlCommand()
With com
.Connection = con
.CommandType = query
.Parameters.AddWithValue("#colProg", cmbProg.SelectedItem.ToString)
.Parameters.AddWithValue("#colMale", txtMaleCut.Text.ToString)
.Parameters.AddWithValue("#colFemale", txtFemaleCut.Text.ToString)
End With
Try
con.Open()
com.ExecuteNonQuery()
Catch ex As SqlException
MessageBox.Show(ex.Message.ToString(), "Saving data Not Complete")
End Try
End Using
End Using
End Sub
This:
.CommandType = query
should be setting Commandtext, not CommandType. Why set those properties like that in the first place, when you can use the constructor?
Using com As New SqlCommand(query, con)

incorrect syntax near "=" in vb.net

I am a beginner and really need help. I want to display data from the database and assign the values to the textboxes and a combobox on a form, but I get this error
Incorrect syntax near "="
It appears is on this line
myreader = cmd.ExecuteReader
Please - any help?
Sub ref()
Dim conn As New SqlConnection
conn.ConnectionString = ("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True")
conn.Open()
Dim strsql As String
strsql = "SELECT ProgName,MaleCuteOff,FemaleCutOff from CutOff_Point where ProgName=" + cmbCourse.SelectedItem + ""
Dim cmd As New SqlCommand(strsql, conn)
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
txtFemale.Text = myreader("FemaleCutOff")
txtMale.Text = myreader("MaleCuteOff")
conn.Close()
End Sub
You should always use SQL parameters to pass parameters to SQL - it avoids embarrasing problems like single quotes breaking the query and deliberate SQL injection attacks.
It's probably best to make sure that there is a selected value before trying to use it.
Some things, e.g. database connections, use "unmanaged resources" and it is necessary to use the Dispose() method to make sure that things are cleaned up afterwards. The Using statement is a convenient way to get the computer to take care of that for you.
I didn't see a need for the query to return the value that was passed to it (ProgName).
You will need to adjust the .SqlDbType and .Size to match the database column.
Option Strict On
' ... other code
Sub Ref()
If cmbCourse.SelectedIndex >= 0 Then
Dim sql As String = "SELECT MaleCuteOff, FemaleCutOff FROM CutOff_Point WHERE ProgName = #ProgName"
Dim connStr = "Data Source=.\;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True"
Using conn As New SqlConnection(connStr),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#ProgName", .SqlDbType = SqlDbType.VarChar, .Size = 99, .Value = cmbCourse.SelectedItem})
conn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
txtFemale.Text = rdr.GetInt32(0).ToString()
txtMale.Text = rdr.GetInt32(1).ToString()
End If
End Using
End If
End Sub
P.S. Shouldn't UEW_ADMISSION_CHEAKER be UEW_ADMISSION_CHECKER? It's best to have things spelt correctly as it is easier to type them.
First of all this Block of Code is not OK. You could use :
Using....End Using Method.
SqlCommand.Parameters Property for security issues.
Connection Strings and Configuration Files for security issues.
Allow me to rewrite your Code using the above methods.
Private Sub RetrieveAndDisplayCutOff()
Dim sbMale As New StringBuilder
Dim sbFemale As New StringBuilder
Dim strsql As String =
"SELECT MaleCutOff,FemaleCutOff FROM CutOff_Point WHERE ProgName = #ComboItem"
Using conn As New SqlConnection("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True"),
CMD As New SqlCommand(strsql, conn)
CMD.Parameters.Add("#ComboItem", SqlDbType.VarChar).Value = ComboBox1.SelectedItem.ToString
conn.Open()
Using MyReader As SqlDataReader = CMD.ExecuteReader
While MyReader.Read 'Returns False if no more rows
'OP mentioned in comments that these fields were int
sbMale.AppendLine(MyReader.GetInt32(0).ToString)
sbFemale.AppendLine(MyReader.GetInt32(1).ToString)
End While
End Using
End Using
txtMale.Text = sbMale.ToString
txtFemale.Text = sbFemale.ToString
End Sub

Search Another Type Text SQL Server VB.Net

I have a problem with search: how do I search our language text from SQL query and which type data I select
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "SELECT * FROM Table_12 WHERE m='" & "دولت خان" & "'"
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() > 0 Then
TextBox2.Text = table.Rows(0)(1).ToString()
MessageBox.Show("Record found!")
Else
MessageBox.Show("Record not found!")
Keep your database objects local so you can control that they are closed and disposed. A single Using...End Using block handles this for you.
You can pass your connection string directly to the constructor of the connection and pass the command text and connection directly to the constructor of the command.
Always use parameters to avoid Sql Injection. The value concatenated to an sql command string is potentially executable. Parameter values are not.
Private Sub OpCode()
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("SELECT * FROM Table_12 WHERE m= #m;", cn)
cmd.Parameters.Add("#m", SqlDbType.NVarChar, 50).Value = "دولت خان"
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count() > 0 Then
TextBox2.Text = dt.Rows(0)(1).ToString()
MessageBox.Show("Record found!")
Else
MessageBox.Show("Record not found!")
End If
End Sub
Search with like clause for unicode in column m and show column o:
cmd.CommandText = "SELECT o FROM Table_12 WHERE m like N'%" & "دولت خان" & "%'"

SQL Server cursor to vb.net

everyone, How can I read a cursor from a stored procedure?
This is my code, but it's not working
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conexionBD").ToString())
Public Function LoadData() As String
Dim strQuery As String
strQuery = "Kardex_P''"
Using (con)
Dim sqlComm As SqlCommand = New SqlCommand(strQuery, con)
con.Open()
Dim sqlReader As SqlDataReader = sqlComm.ExecuteReader()
If sqlReader.HasRows Then
While (sqlReader.Read())
txtReporte = sqlReader.ToString
End While
End If
End Using
Return txtReporte
End Function
Please I need your help.
Thanks in advance
The cursor code will live in the stored procedure that ultimately returns a set of rows to read. Reference each column by ordinal value or name:
txtReporte.Text = sqlReader(0).ToString()
or
txtReporte.Text = sqlReader("YourColumnName").ToString()
What is wrong in OP code and how to fix it.
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conexionBD").ConnectionString
''//.ToString()) wrong but not fatal
Public Function LoadData() As String
Dim txtReporte as String = "" ''//you return this so declare
Dim strQuery As String
strQuery = "Kardex_P" ''//"Kardex_P''" This supposed to be SP name. What '' do inside?
Using (con) ''//this is good
Dim sqlComm As SqlCommand = New SqlCommand(strQuery, con)
''//By default command type is text so next line is critical
sqlComm.CommandType = CommandType.StoredProcedure
con.Open()
Dim sqlReader As SqlDataReader = sqlComm.ExecuteReader()
''//If sqlReader.HasRows Then checking "HasRows is redundant here
While (sqlReader.Read())
''//txtReporte = sqlReader.ToString no comment
txtReporte &= sqlReader("SomeField")
End While
''//End If
con.Close() ''//cleanup recommended
End Using
Return txtReporte
End Function
I hope this will work. Not perfect of course.

Resources