Displaying data from a dataset vb.net - sql-server

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

Related

How can I solve a max pool size - ASP.NET

Public Function QueryDataSet(ByVal strSQL As String) As DataSet
Dim ds As New DataSet
Dim dtAdapter As New SqlDataAdapter
objConn = New SqlConnection
With objConn
.ConnectionString = strConn
.Open()
End With
objCmd = New SqlCommand
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
End With
dtAdapter.SelectCommand = objCmd
dtAdapter.Fill(ds)
objConn.Close()
objConn.Dispose()
SqlConnection.ClearPool(objConn)
objConn = Nothing
Return ds
End function
The above is in the class
How can I fix my function that solve the Max Pool Size is Full on my server?
Please Help me.
Use following code
Public Function QueryDataSet(ByVal strSQL As String) As DataSet
Dim ds As New DataSet
Dim dtAdapter As New SqlDataAdapter
Try
objConn = New SqlConnection
With objConn
.ConnectionString = strConn
.Open()
End With
objCmd = New SqlCommand
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
End With
dtAdapter.SelectCommand = objCmd
dtAdapter.Fill(ds)
objConn.Close()
objConn.Dispose()
SqlConnection.ClearPool(objConn)
objConn = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
objConn.Close()
objConn.Dispose()
SqlConnection.ClearPool(objConn)
objConn = Nothing
End Try
Return ds
End function
or Add MaxPoolSize=abc in the Connection String.

getting Count(Record) result to a variable in VB.Net

I want to capture count of record to a variable but code is not working. Please assist
Dim PrevRgAPAC As Integer
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = "Data Source=XXXXXXXXXXX; initial catalog=XXXXXXXXXXXX; Integrated Security=true"
cmd.Connection = con
con.Open()
cmd.CommandText = "select count(record) from tblKPI where user_region='APAC' AND payroll_month='February'"
rd = cmd.ExecuteReader
If rd.HasRows Then
rd.Read()
PrevRgAPAC = rd.Item("exec")
Else
MsgBox("Not Found")
End If
Thank you
Try to use SqlCommand.ExecuteScalar Method:
PrevRgAPAC = Convert.ToInt32(cmd.ExecuteScalar())
Assuming that PrevRgAPAC is the variable in which you want to store the value of count. So your code would look like this:
Dim PrevRgAPAC As Int32 = 0
Dim sql As String = "select count(record) from tblKPI where user_region='APAC' AND payroll_month='February'"
Using conn As New SqlConnection("Data Source=XXXXXXXXXXX; initial catalog=XXXXXXXXXXXX; Integrated Security=true")
Dim cmd As New SqlCommand(sql, conn)
Try
conn.Open()
PrevRgAPAC = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using

Populate Combobox from SQL Server vb.net

I'm trying to populate a combobox with data from SQL Server. This is my code so far. There are asterisks around the errors. Also, ignore the comments.
Private Sub frmOriginal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connetionString As String = Nothing
Dim sqlcon As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
connetionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
sql = "select * from TickerSymbol"
sqlcon = New SqlConnection(connetionString)
Try
sqlcon.Open()
command = New SqlCommand(sql, sqlcon)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
sqlcon.Close()
cboID.DataSource = ds.Tables(0)
cboID.ValueMember = "TickerSymbol"
cboID.DisplayMember = "TickerSymbol"
Catch ex As Exception
'MessageBox.Show("Can not open connection ! ")'
End Try
End Sub
Private Sub cboID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboID.SelectedIndexChanged
Dim dr As SqlDataReader
Dim command As New SqlCommand *(queryString, connection)*
Dim dataReader As SqlDataReader = command.ExecuteReader()
Dim sqlcon As SqlConnection
Dim cmd As SqlCommand
sqlcon = New SqlConnection
sqlcon.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
Try
sqlcon.Open()
cmd = New SqlCommand
cmd.CommandText = " select * from TickerSymbol where TickerSymbol = '" & cboID.Text & "'"
cmd = New SqlCommand(cmd.CommandText, sqlcon)
dr = cmd.ExecuteReader
While dr.Read()
'TxtID.Text = dr.GetInt32(0)'
'TxtSN.Text = dr.GetString(1)'
'TxtGender.Text = dr.GetString(2)'
'TxtPhone.Text = dr.GetInt32(3)'
'TxtAdrress.Text = dr.GetString(4)'
lblCompanyName.Text = dataReader.GetString(1)
lblPurchasePrice.Text = dataReader.GetSqlMoney(2)
lblQtyPurchased.Text = dataReader.GetInt32(3)
lblPurchaseDate.Text = dataReader.GetDateTime(4)
End While
sqlcon.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
sqlcon.Dispose()
End Sub
Please use parameterized queries as this will format values properly e.g. apostrophes in text will escape properly with parameters while without you must handle them, dates will be formatted properly too. Code is much cleaner also.
Example, syntax for Framework 3.5 and higher. If a connection string is used more than once then consider placing it in a private variable or under My.Settings under project properties.
Using cn As New SqlConnection With {.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"}
Using cmd As New SqlCommand With {.Connection = cn, .CommandText = "select * from TickerSymbol where TickerSymbol = #TickerSymbol"}
cmd.Parameters.AddWithValue("#TickerSymbol", cboID.Text)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
'
'
'
End While
End If
End Using
End Using

Why does my VB.NET Function shows a warning

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.

VB .NET and Databases

Trying to get this bit of code to enter a player name fill it in the datarow then update it in the DB. It currentley updates in the datarow but I can not get the code right to update the DB. Could you please help cheers.
Using da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM Team1", con)
da.Fill(ds, "BPAWA")
txtFirstName.Text = ds.Tables("BPAWA").Rows(0).Item(1)
T1P1 = InputBox("Name of Player 1")
ds.Tables("BPAWA").Rows(0).Item(1) = T1P1
ds.Tables("BPAWA").AcceptChanges()
ds.AcceptChanges()
da.Update(ds, "BPAWA")
MsgBox("Player 1 Added Successfully")
End Using
You OleDbDataAdapter is not linked to an actual command neither you seem to have created the adapter in your code. See an example here
Missing a line like this
Dim da As OleDbDataAdapter = new OleDbDataAdapter(selectCommand, connection);
so I could rewrite your code in this way (Avoiding the global variables)
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim dbProvider As String = "PROVIDER=microsoft.ace.oledb.12.0;"
Dim dbSource As String = "Data Source = C:\BP_Table_Project.accdb"
Dim ds as DataSet = new DataSet()
Using con As OleDbConnection = new OleDbConnection()
con.ConnectionString = dbProvider & dbSource
con.Open()
MsgBox("Connection With Database Established", 0, "Database Connection")
Using da as OleDbDataAdapter = new OleDbDataAdapter("SELECT * FROM Team1", con)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "BPAWA")
......
da.Update(ds, "BPAWA")
MsgBox("Player 1 Added Successfully")
End Using
MsgBox("Connection With Database Closed", 0, "Database Connection")
End Using
End Sub
Before da.Update(ds, "BPAWA")
Add:
ds.Tables("BPAWA").AcceptChanges()
ds.AcceptChanges()

Resources