Object reference error setting a string variable - vb.net

When I try to run the following code, I get this error:
Object reference not set to instance of object
conString = "Data Source=HQ10-1CT-PC0; Initial Catalog=CONTACT_DB; Integrated Security=True"
con.ConnectionString = conString
'Problem is on these two lines
Dim messageID As String
messageID = Me.Tag.ToString
sql = "select * from Message_tb where M_ID =#Mess_ID"
Dim cmd As New SqlClient.SqlCommand(sql, con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue(“#Mess_ID", messageID)
con.Open()
cmd.ExecuteNonQuery()
da.SelectCommand = cmd
da.Fill(ds, “myMessage")
'Me.DataGridView1.DataSource = ds.Tables("myMessages")
con.Close()
ViewMessage()
How can I fix this?

Me.Tag doesn't have a value, and therefore calling .ToString() for the missing value is not possible.
Dim messageID As StringD = If(Me.Tag?.ToString(), "")
conString = "Data Source=HQ10-1CT-PC0; Initial Catalog=CONTACT_DB; Integrated Security=True"
sql = "select * from Message_tb where M_ID =#Mess_ID"
Using con As New SqlConnection(conString), _
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add(“#Mess_ID", SqlDbType.NVarChar, 10).Value = messageID
da.SelectCommand = cmd
da.Fill(ds, “myMessage")
End Using
ViewMessage()

Related

SQL Error Regarding apostrophe from datagridview using parameter in query

Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0))
end with
The value from the datagrid view contains an apostrophe where I get an error in ('s). Any work around with this?
EDIT:
This is the error:
SqlException was unhandled. Incorrect syntax near 's'.
EDIT 2: i've revised the code to this:
for 1=0 to datagridview.rows.count -1
Dim tname = datagridview.Rows(i)
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0).value)
end with
con.Close()
con.Open()
If Not cmd.ExecuteNonQuery() > 0 Then
con.Close()
Exit For
End If
next
Error is still the same.
As it goes through all the values quickly in one go, I would make the connection once and change the value of the parameter for each iteration, like this:
Dim sql = "INSERT INTO [Schedule] ([Name]) VALUES(#sc)"
Using conn As New SqlConnection("your connection string"),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#sc",
.SqlDbType = SqlDbType.NVarChar,
.Size = -1})
conn.Open()
For i = 0 To dgv.Rows.Count - 1
Dim tname = dgv.Rows(i).Cells(0).Value.ToString()
cmd.Parameters("#sc").Value = tname
cmd.ExecuteNonQuery()
Next
End Using
Including the size of the parameter in its declaration helps SQL Server keep things tidy (it only needs one entry in the query cache).
The Using statement makes sure that the connection and command are disposed of properly when they are finished with.
The purpose of checking If Not cmd.ExecuteNonQuery() > 0 was not clear to me, so I didn't put that in.
(I used "dgv" as the name of the DataGridView.)
Try to replace the " ' " by " '' "
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", replace(sc.cells(0), "'", "''")
end with
/**** EDIT ****/
I will consider by the way that your code have a problem with the affectation of the value. You get the value into SC then try to get again the value from cell
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters("#sc").value = sc.replace("'", "''")
end with

How can I insert an image from SQL Server onto a button in VB.net?

I am having issues assigning an image to every button according to my database.
My current code:
Dim strsql As String
Dim ImgSQl As Image
Dim con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Image FROM Inventory WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSQl = myreader("Image")
con.Close()
btn1.Image = ImgSQl
This is the error I'm getting:
Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'
All I had to do was dim as Byte, also adding "()" is really important for it to work. Hope answering my own question helps a VB.net beginner out there.
Dim strsql As String
Dim ImgSql() As Byte
Using con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Image FROM Inventory WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSql = myreader("Imagen")
Dim ms As New MemoryStream(ImgSql)
btn1.Image = Image.FromStream(ms)
con.Close()
End Using

Trying to use grid view with my data, but it outputs an error

Following is the code am using to bind the grid, can anyone please suggest me what am doing wrong in this snippet
Dim con As New SqlClient.SqlConnection
Dim ds As New DataSet
Dim adapter As SqlDataAdapter
Dim sql As String
con.ConnectionString = "Data Source=SHAHRUKH-PC\SQLEXPRESS;Initial Catalog=vb;User ID=sa;Password=sa#1234"
con.Open()
sql = "Data Source=SHAHRUKH-PC\SQLEXPRESS;Initial Catalog=vb;User ID=****;Password=*****"
cmd.CommandText = "select * From demo_vb Where ID = '" & txtbox4.Text & "'"
adapter = New SqlClient.SqlDataAdapter
adapter.Fill(ds)
GridView1.ItemsSource = New DataView()
GridView1.DisplayMemberPath = "ID"
con.Close()
I get this error:
The SelectCommand property has not been initialized before calling 'Fill'
try following code:
SqlCommand cmd;
SqlConnection con = new SqlConnection("Data Source=SUNTECH-PC\\SQLEXPRESS;Initial Catalog=iSense;Integrated Security=True;");
con.Open();
cmd = new SqlCommand("Select Picture from Images",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
I think this would help
Dim con As New SqlClient.SqlConnection("Data Source=SHAHRUKH-PC\SQLEXPRESS;Initial Catalog=vb;User ID=sa;Password=sa#1234")
Dim ds As New DataSet
Dim sql As New SqlCommand("select * From demo_vb Where ID = '" & txtbox4.Text & "'",con)
Dim adapter As New SqlDataAdapter(sql)
con.Open()
adapter.Fill(ds)
GridView1.datasource = ds.Tables(0)
GridView1.databind()
con.Close()

ADD SQL QUERY STAT

I'm trying to update the records from textboxes into the Access database, I'm wondering every time I hit save, it generates an error
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
Highlighting .ExecuteNonQuery()
What does it mean? It's preventing me to run my code :(
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
"SET FirstName=empFname, LastName=empLname, Department=empDept, " & _
"Status=empStat, Years=empYears " & _
"WHERE empID=empNum"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("FirstName", empFname)
.Parameters.AddWithValue("LastName", empLname)
.Parameters.AddWithValue("Department", empDept)
.Parameters.AddWithValue("Status", empStat)
.Parameters.AddWithValue("Years", empYears)
.ExecuteNonQuery()
End With
Using cmd2 = New OleDbCommand(sqlQuery, con)
cmd.Parameters.AddWithValue("FirstName", empFname)
cmd.Parameters.AddWithValue("LastName", empLname)
cmd.Parameters.AddWithValue("Department", empDept)
cmd.Parameters.AddWithValue("Status", empStat)
cmd.Parameters.AddWithValue("Years", empYears)
cmd.ExecuteNonQuery()
End Using
sqlQuery = "SELECT * FROM tbl_empinfo "
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
With cmd1
.CommandText = sqlQuery
.Connection = con
With SqlAdapter
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
con.Close()
End Sub
You are trying to set an UPDATE command text for the SelectCommand of the Adapter. This, of course has no way to be successful. Last but not least the UPDATE command text doesn't contain a WHERE clause, and so, if executed, it updates every record in the table tbl_empinfo with the same data.
In this context there is no need to use an adapter. You could simply execute the command, providing an appropriate WHERE clause and the values for the other parameters
Dim sqlQuery As String = "UPDATE tbl_empinfo " & _
"SET FirstName=?, LastName=?, Department=?, " & _
"Status=?, Years=? " & _
"WHERE empID=?"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("#p1", empFName)
.Parameters.AddWithValue("#p2", empLName)
.Parameters.AddWithValue("#p3", empDept)
.Parameters.AddWithValue("#p4", empStat)
.Parameters.AddWithValue("#p5", empYears)
.Parameters.AddWithValue("#p6", empNum)
.ExecuteNonQuery()
End With
After this you could call the code that reloads the data to fill your grid
sqlQuery = "SELECT * FROM tbl_empinfo"
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim Table As New DataTable
With cmd1
.CommandText = sqlQuery
.Connection = con
With da
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Notice that I have changed the name of the command and the adapter to a less confusing names. SqlCommand And SqlDataAdapter are the names of the classes equivalent to the OleDbCommand and OleDbDataAdapter but used for Sql Server. At first sight I was thinking that you were trying to use the SqlClient classes to update an MS-Access database.

how to fill system.data.dataset from oracle.dataacess.client.oracledataadapter?

I have installed Oracle 10g Express Edition database on a server and install the client on my PC.
Now, I`m developing a vb.net application using visual studio 2005 and I need to use the oracle 10g express edition database. So I initialize the connection using the following connection string:
_connectionString = "User Id=Graphya;Password=Graphya;Data Source=gis64:1522/XE;"
Then I define new OracleDataAdapter, and I use the following code to fill a dataset:
Dim insertCommand As OracleCommand = New OracleCommand()
Dim commandTextTemplate As String = "INSERT INTO {0}(" & g_pfldUsername & ", " & g_pfldSubject & ") VALUES (?, ?)"
insertCommand.CommandText = String.Format(commandTextTemplate,TABLE_NAME)
insertCommand.Connection = Me.Connection
insertCommand.Parameters.Add(New Oracle.DataAccess.Client.OracleParameter(g_pfldUsername, Oracle.DataAccess.Client.OracleDbType.Varchar2, 50, g_pfldUsername))
insertCommand.Parameters.Add(New Oracle.DataAccess.Client.OracleParameter(g_pfldSubject, Oracle.DataAccess.Client.OracleDbType.Varchar2, 50, g_pfldSubject))
_OracleDataAdapter.InsertCommand = insertCommand
_OracleDataAdapter.Fill(_dataSet, TABLE_NAME)
So after debugging this code I got the following error:
Unable to cast object of type 'Oracle.DataAccess.Client.OracleCommand' to type 'System.Data.Common.DbCommand'.
#Davideg: my code is c# to fill data set
OleDbConnection cnOra = new OleDbConnection("Provider=MSDAORA;Data Source=myOracleServer;"
+ "user id=myUID;password=myPWD;"
+ "persist security info=false;");
OleDbCommand cmdPerson = new OleDbCommand
+ ("{call PackPerson.allPerson({resultset 3, ssn, fname, lname})}", cnOra);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmdPerson);
cnOra.Open();
DataSet ds = new DataSet();
daPerson.Fill(ds,"Person");
this.dataGrid1.DataSource = ds.Tables["Person"];
cnOra.Close();
Function GetEmailsByPageName(ByVal pageName As String) As DataSet
Dim cn As New OracleConnection
Dim cmd As New OracleCommand
cn = New OracleConnection
cn.ConnectionString = (ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
cmd = New OracleCommand("ORACLEDBA.PACKAGE_EMAIL.SP_EMAIL_LISTING_BY_NAME")
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Connection = cn
cmd.BindByName = True
Dim paramCursor As OracleParameter = New OracleParameter("email_list_cursor", OracleDbType.RefCursor)
With cmd.Parameters
.Add(New OracleParameter("a_page_name", OracleDbType.Varchar2)).Value = pageName
.Add("a_err_code", OracleDbType.Int32, Data.ParameterDirection.Output)
.Add("a_err_msg", OracleDbType.Varchar2, 300).Direction = Data.ParameterDirection.Output
.Add(paramCursor).Direction = Data.ParameterDirection.Output
End With
Dim da As New OracleDataAdapter(cmd)
Dim dsEmail As DataSet = New DataSet
Try
da.SelectCommand = cmd
da.Fill(dsEmail)
Return dsEmail
Catch ex As Exception
Throw
Finally
da.Dispose()
cmd.Dispose()
cn.Dispose()
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
End Function