Public Function Delete_GST_Entry(ByVal GE_ID As Integer) As DataTable
Try
Using con As New SqlConnection(DF_Class.GetConnectionString())
Dim ds As DataTable = New DataTable
con.Open()
Dim command As SqlCommand = New SqlCommand("Delete_GSTEntry", con)
command.Parameters.AddWithValue("GE_ID", GE_ID)
command.CommandType = CommandType.StoredProcedure
Dim adapter As SqlDataAdapter = New SqlDataAdapter(command)
Dim table As DataTable = New DataTable
adapter.Fill(ds)
Return ds
con.Close()
End Using
Catch ex As SqlException
MessageBox.Show(ex.Message, "Data Input Error")
End Try
End Function
I am getting a warning saying that a NULL reference could occur. What is the mistake I am doing?
Warning:
"Function 'Delete_GST_Entry' doesn't return a value on all code paths.
A null reference exception could occur at run time when the result is
used. "
All exit points (return paths) of a method must return what the method's signature specifies.
Re-write like this:
Public Function Delete_GST_Entry(ByVal GE_ID As Integer) As DataTable
Dim dt As DataTable = New DataTable
Try
Using con As New SqlConnection(DF_Class.GetConnectionString())
con.Open()
Dim command As SqlCommand = New SqlCommand("Delete_GSTEntry", con)
command.Parameters.AddWithValue("GE_ID", GE_ID)
command.CommandType = CommandType.StoredProcedure
Dim adapter As SqlDataAdapter = New SqlDataAdapter(command)
adapter.Fill(dt)
con.Close()
End Using
Catch ex As SqlException
MessageBox.Show(ex.Message, "Data Input Error")
End Try
Return dt ' Note will be empty if stored proc call fails...
End Function
Ideally, you should wrap the connection in a using statement.
Related
I have images assigned to every button in my VB.NET form, the images come from SQL Server. The data type is varbinary(MAX).
This is my code:
Using con As New SqlConnection("con string")
Dim sql As String = "SELECT * FROM Inventory WHERE ID=#ID"
Using cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 3
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Image")) Then
Boton3.Text = myreader("Item")
Boton3.Enabled = myreader("ONOFF")
Dim ImgSql() As Byte = DirectCast(myreader("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton3.BackgroundImage = Image.FromStream(ms)
con.Close()
End Using
Else
Boton3.Text = myreader("Item")
Boton3.BackgroundImage = Nothing
Boton3.Enabled = myreader("ONOFF")
End If
End Using
End Using
End Using
The platform is 64bit. I'm thinking it might have to do with not disposing properly, but I'm not sure since I'm new to coding.
EDIT SHOWING NEW CODE AND HOW I RETRIVE MORE THAN ONE RECORD:
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Dim dt As DataTable
Try
dt = GetInventoryDataByID(1)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
Boton1.Text = dt.Rows(0)("Articulo").ToString
Boton1.Enabled = CBool(dt.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt.Rows(0)("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton1.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton1.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
Dim dt2 As DataTable
Try
dt2 = GetInventoryDataByID(2)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt2.Rows.Count > 0 Then
Boton2.Text = dt2.Rows(0)("Articulo").ToString
Boton2.Enabled = CBool(dt2.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt2.Rows(0)("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(dt2.Rows(0)("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton2.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton2.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
End Sub
Private Function GetInventoryDataByID(id As Integer) As DataTable
Dim dt As New DataTable
Dim sql As String = "SELECT Imagen, Articulo, ONOFF FROM Inventario WHERE ID=#ID"
Using con As New SqlConnection("CON STRING"),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
dt.Load(myreader)
End Using
End Using
Return dt
End Function
End Class
You don't want to hold a connection open while you update the user interface. Separate you user interface code from your database code.
If you put a comma at the end of the first line of the outer Using block, both the command and the connection are included in same block. Saves a bit of indenting.
You are passing an integer to the #ID parameter but you have set the SqlDbType as a VarChar. Looks like a problem. I changed the SqlDbType to Int.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DataTable
Try
dt = GetInventoryDataByID(3)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
Boton3.Text = dt.Rows(0)("Item").ToString
Boton3.Enabled = CBool(dt.Rows(0)("ONOFF"))
If Not DBNull.Value.Equals(dt.Rows(0)("Image")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
Boton3.BackgroundImage = Image.FromStream(ms)
End Using
Else
Boton3.BackgroundImage = Nothing
End If
Else
MessageBox.Show("No records returned")
End If
End Sub
Private Function GetInventoryDataByID(id As Integer) As DataTable
Dim dt As New DataTable
Dim sql As String = "SELECT * FROM Inventory WHERE ID=#ID"
Using con As New SqlConnection("con string"),
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
dt.Load(myreader)
End Using
End Using
Return dt
End Function
EDIT Add Dispose on image
If Not DBNull.Value.Equals(dt.Rows(0)("Image")) Then
Dim ImgSql() As Byte = DirectCast(dt.Rows(0)("Image"), Byte())
Using ms As New MemoryStream(ImgSql)
If Boton3.BackgroundImage IsNot Nothing Then
Boton3.BackgroundImage.Dispose()
End If
Boton3.BackgroundImage = Image.FromStream(ms)
End Using
Else
If Boton3.BackgroundImage IsNot Nothing Then
Boton3.BackgroundImage.Dispose()
End If
End If
I resolved this issue by simply not using buttons. Instead I used pictureboxes as buttons and that resolved the issue. Im guesssing the problem is that buttons don't allow as much memory as pictureboxes.
I am trying to get multiple data sets from SQL Server using a VB.NET application. The problem that every time I try to execute the query,
I get this message:
Cannot change property 'ConnectionString'. The current state of the connection is open
Then I tried to fix it by enabling MARS
<connectionStrings>
<add name="ConString"
providerName="System.Data.SqlClient"
connectionString="Data Source=my-PC;Initial Catalog=Project;Persist Security Info=True; MultipleActiveResultSets=true;User ID=user;Password=*****" />
</connectionStrings>
This is my code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj, body
obj = TextBox1.Text
body = TextBox2.Text
For Each mail In getemail()
Send_mail(mail, obj, body, getattachment(mail))
Next
MsgBox("Traitement effectué")
End Sub
Function getemail() As List(Of String)
Dim strMailTo As New List(Of String)
Dim SQL As String = "Select EMail FROM [USER] WHERE EMail Is Not NULL And MatriculeSalarie Is Not NULL And [EMail] <> '' and EtatPaie = 3 and BulletinDematerialise = 1 "
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
Dim dr As DataRow
Try
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Using sda As New SqlDataAdapter(cmd)
Using ds As New DataTable()
sda.Fill(ds)
sqLdr = cmd.ExecuteReader()
For i = 0 To ds.Rows.Count - 1
dr = ds.Rows(i)
strMailTo.Add(dr("EMail"))
Next
End Using
End Using
Return strMailTo
sqLdr.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
closeCon()
Return strMailTo
End Function
Function getattachment(email) As String()
Dim SQL As String = "Select MatriculeSalarie FROM [USER] WHERE [EMail]='" & email & "'"
Dim cmd As New SqlCommand
Dim sqLdr As SqlDataReader
ConnServer()
cmd.Connection = con
cmd.CommandText = SQL
Dim mat As String
mat = ""
Dim Dir As String = ConfigurationManager.AppSettings("path1").ToString
Dim file()
sqLdr = cmd.ExecuteReader()
While sqLdr.Read
mat = sqLdr.GetValue(sqLdr.GetOrdinal("MatriculeSalarie"))
End While
file = IO.Directory.GetFiles(Dir, mat.Substring(1) & "*.pdf")
sqLdr.Close()
Return file
End Function
If all you are going to do is show a message box in a Catch, don't do it in the database code. Let the error bubble up to the user interface code and put the Try around where the method is called.
Do not declare variables without a DataType. The button code with Option Infer on sets the type of obj and body.
Private ConStr As String = "Your connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim obj = TextBox1.Text
Dim body = TextBox2.Text
Dim emails As New List(Of String)
Try
emails = getemail()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error retrieving email list")
Exit Sub
End Try
For Each email In emails
Try
Send_mail(email, obj, body, getattachment(email))
Catch ex As Exception
MessageBox.Show(ex.Message, "Error getting attachments")
End Try
Next
MessageBox.Show("Traitement effectué")
End Sub
Parameters used by Sub and Function must have a DataType.
I don't know what you are doing here.
While sqLdr.Read
mat = sqLdr.GetValue(sqLdr.GetOrdinal("MatriculeSalarie"))
End While
Each iteration will overwrite the previous value of mat. I can only assume that you expect only a single value, in which case you can use ExecuteScalar to get the first column of the first row of the result set. Don't do anything with the data until after the connection is closed. Just get the raw data and close (End Using) the connection. Manipulate the data later.
Always use Parameters. Parameters are not treated as executable code by the database server. They are simply values. An example of executable code that could be inserted is "Drop table [USER];" where the value of a parameter belongs. Oops!
Function getemail() As List(Of String)
Dim SQL As String = "Select EMail FROM [USER]
WHERE EMail Is Not NULL
And MatriculeSalarie Is Not NULL
And [EMail] <> ''
And EtatPaie = 3
And BulletinDematerialise = 1;"
Dim dt As New DataTable
Using con As New SqlConnection("Your connection string"),
cmd As New SqlCommand(SQL, con)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Dim strMailTo As New List(Of String)
strMailTo = (From row As DataRow In dt.AsEnumerable
Select row.Field(Of String)(0)).ToList
Return strMailTo
End Function
Function getattachment(email As String) As String()
Dim SQL As String = "Select MatriculeSalarie FROM [USER] WHERE [EMail]='" & email & "'"
Dim mat As String
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand(SQL, con)
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = email
con.Open()
mat = cmd.ExecuteScalar().ToString()
End Using
Dim Dir As String = ConfigurationManager.AppSettings("path1").ToString
'Your original code was fine, no need for searchPattern.
'I added this so you could see if your search pattern was what you expected.
Dim searchPattern = mat.Substring(1) & "*.pdf"
Debug.Print(searchPattern) 'Appears in the Immediate window
Dim file = IO.Directory.GetFiles(Dir, searchPattern)
Return file
End Function
I'm trying to retrieve binary data from a database.
I got this error: "Error: Fill: selectcommand.connection property has not been". I can't locate the error.
Public Shared Function BinaryData(ByVal sFileName As String) As Byte()
Dim strSql As String
Dim binaryFile As Byte() = Nothing
Dim dt As DataTable
Dim myCommand As New SqlCommand
Dim sqlConn As New SqlConnection
sqlConn = New SqlConnection("Data Source=xxx;Initial Catalog=xx;Persist Security Info=True;User ID=wxx;Password=xx;MultipleActiveResultSets=True;Application Name=EntityFramework")
sqlConn.Open()
myCommand.Connection = sqlConn
strSql = "SELECT Data FROM tbldrive WHERE Filename = '" + sFileName + "'"
Dim scmd As New SqlCommand(strSql, sqlConn)
dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)
If dt.Rows.Count > 0 Then
Try
binaryFile = DirectCast(dt.Rows(0).Item("Data"), Byte())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Return binaryFile
End Function
It looks like you've tried a few things in that code but accidentally left the remains of some attempts in there.
There are some things you could do a bit differently: as you're only after one item from the database, you can use ExecuteScalar; and when the code has finished with the SQL connection and command, they should have .Dispose() called on them - the Using statement will take care of that for you even if something goes wrong. Finally, you should always use SQL parameters to pass parameters to an SQL query - it makes it more secure and avoids having to worry about things like apostrophes in the value.
Public Shared Function BinaryData(ByVal sFileName As String) As Byte()
Dim sql As String = "SELECT Data FROM tbldrive WHERE Filename = #fname"
Dim connStr = "Data Source=xxx;Initial Catalog=xx;Persist Security Info=True;User ID=wxx;Password=xx;MultipleActiveResultSets=True;Application Name=EntityFramework"
Dim binaryFile As Byte() = Nothing
Using conn As New SqlConnection(connStr),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {
.ParameterName = "#fname",
.SqlDbType = SqlDbType.NVarChar,
.Size = 255,
.Value = sFileName})
conn.Open()
Dim obj As Object = cmd.ExecuteScalar()
If obj IsNot Nothing Then
Try
binaryFile = DirectCast(obj, Byte())
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Using
Return binaryFile
End Function
(You may need to adjust the .SqlDbType and .Size parameters: they need to match the column type and size in the database. Also, you probably don't need MultipleActiveResultSets.)
The problem seems to be that you have two SqlCommand objects:
Dim myCommand As New SqlCommand
...
myCommand.Connection = sqlConn
It's assigned but not used.
Then you have defined another one:
Dim scmd As New SqlCommand(strSql, sqlConn)
that is not used either.
And I don't know why you have this:
dt = DataComponent.DataTableQuery(DataComponent.SqlConn, strSql)
Do you even need a SqlCommand if you are not using it ?
Clean up your code by removing unused variables.
I made two comboboxes. One of them depends on data from the other. When the first one selected index changes I need take the new value and use it to update the other. Here is what I have so far for the first combobox:
Try
Dim cmd As New SqlCommand("select * from tb_section ", connSql)
connSql.Open()
Dim dr As New SqlDataAdapter(cmd)
Dim table As New DataTable
dr.Fill(table)
compsec.DataSource = table
compsec.DisplayMember = "sec_name"
compsec.ValueMember = "sec_code"
Catch ex As Exception
MsgBox(ex.Message)
connSql.Close()
Finally
connSql.Close()
End Try
And here is code for the other combo box:
Public Sub all_group_list(sectioncode)
Try
Dim cmd As New SqlCommand("select * from tb_group where sec_code= " & sectioncode.ToString, connSql)
connSql.Open()
Dim dro As New SqlDataAdapter(cmd)
Dim table As New DataTable
dro.Fill(table)
compgroup.DataSource = table
compgroup.DisplayMember = "group_name"
compgroup.ValueMember = "group_code"
Catch ex As Exception
MsgBox(ex.Message)
connSql.Close()
Finally
connSql.Close()
End Try
End Sub
When the first combobox index changes I run this code:
Private Sub compsec_SelectedIndexChanged(sender As Object, e As EventArgs) Handles compsec.SelectedIndexChanged
connSql.Close()
all_group_list(compsec.SelectedValue.ToString)
End Sub
It's not clear what problem you're actually having, but there are several fixes in the code below. Name: don't use string concatenation to put data into an SQL command! Also, don't try to re-use the same connection object throughout an application. Only share the connection string, as sharing the same connection object interferes with the connection pooling feature in ADO.Net. Further, the DataAdapter will handle opening and closing the connection for you, and a Using block, rather than a Finally block, is the best way to be sure the connection closes if an exception is thrown.
Try
Dim ds As New DataSet
Using cn As new SqlConnection(connSql.ConnectionString), _
cmd As New SqlCommand("select sec_name, sec_code from tb_section", cn), _
da As New SqlDataAdapter(cmd)
da.Fill(ds)
End Using
compsec.DisplayMember = "sec_name"
compsec.ValueMember = "sec_code"
compsec.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.Message)
End Try
.
Public Sub all_group_list(sectioncode)
Try
Dim ds As New DataSet
Using cn As New SqlConnection(connSql.ConnectionString), _
cmd As New SqlCommand("select group_name, group_code from tb_group where sec_code= #SectionCode", cn), _
da As New SqlDataAdapter(cmd)
'Had to guess at column type/length here. Use the actual column definition from your database
cmd.Parameters.Add("#SectionCode", SqlDbType.NVarChar, 10).Value = sectioncode
da.Fill(ds)
End Using
compgroup.DisplayMember = "group_name"
compgroup.ValueMember = "group_code"
compgroup.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
.
Private Sub compsec_SelectedIndexChanged(sender As Object, e As EventArgs) Handles compsec.SelectedIndexChanged
all_group_list(compsec.SelectedValue.ToString())
End Sub
I am having issues returning data from a MS SQL database.
The code is returning 'System.data.datarowview' instead of the results of my query. The code for the sub is:
Public Sub newquery(query As String)
Dim SQLConn As SqlConnection = New SqlConnection
Dim SqlCommand As New SqlCommand
SQLConn.ConnectionString = "Data Source=.\testing;Initial Catalog=eurostyle;Integrated Security=SSPI;"
SqlCommand = New SqlCommand(query, SQLConn)
Try
SQLConn.Open()
sqlDA = New SqlDataAdapter(SqlCommand)
sqlDataset = New DataSet
sqlDA.Fill(sqlDataset)
SQLConn.Close()
listbox1.DataContext = sqlDataset
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I am new to WPF and I'm sure that is only something trivial.
Any help is greatly appreciated!
DataGrid view would be more appropriate to display results from database.
Try this:
Public Sub newquery(query As String)
Dim SQLConn As SqlConnection = New SqlConnection
Dim SqlComm As New SqlCommand
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
Dim sqlDA As New SqlDataAdapter
SQLConn.ConnectionString = "Data Source=.\testing;Initial Catalog=eurostyle;Integrated Security=SSPI;"
Try
SQLConn.Open()
SqlComm = SQLConn.CreateCommand
SqlComm.CommandText = query
SqlComm = New SqlCommand(zapytanie, myConn)
sqlDA.SelectCommand = SqlComm
sqlDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView.DataSource = bSource
sqlDA.Update(dbDataSet)
SQLConn.Close()
Catch ex As SqlException
MessageBox.Show("Query Error: " & ex.Message)
End Try