Need the Syntax for a SQL 'like' Query through VB.net - sql-server

I am using MS SQL and trying to run a query using vb.net
I want to get data like
101
102
...
110
111
...
The Query I executed in MS SQL is
select Book_Code, Book_Name from famsetup where book_code like '1%'
and this runs fine and gives me proper result...
When I write following code in vb.net written below,
ListViewBound(LstViewHelp, "Select Book_Code, Book_Name from FAMSETUP where Book_Code like '1%'", con1)
I don't get any value...
Note:- Listviewbound is my function and properly working on other places in my program, I just showed this full line...
Is my query wrong writing in vb.net???
What query should I write in vb.net???
Any help accepted...! :/
The other codes are
Listviewbound
Sub ListViewBound(lvw As ListView, QRY As String, Xcn As SqlConnection)
Try
cmd = New SqlCommand(QRY, Xcn)
da = New SqlDataAdapter(cmd)
dt = New DataTable
Dim ListView1 As ListView = New ListView
da.Fill(dt)
lvw.View = View.Details
lvw.GridLines = True
lvw.Columns.Clear()
lvw.Items.Clear()
For Each col As DataColumn In dt.Columns
lvw.Columns.Add(col.ToString)
Next
For Each row As DataRow In dt.Rows
Dim lst As ListViewItem
lst = lvw.Items.Add(If(row(0) IsNot Nothing, row(0).ToString, ""))
For i As Integer = 1 To dt.Columns.Count - 1
lst.SubItems.Add(If(row(i) IsNot Nothing, row(i).ToString, ""))
Next
Next
For i = 0 To lvw.Items.Count - 1
If i Mod 2 Then
lvw.Items(i).BackColor = Color.White
Else
lvw.Items(i).BackColor = Color.LightBlue
End If
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
The Connection string Code
Sub CompDb_Open()
Try
con1.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=bonny;Integrated Security=True"
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

Related

How to filter datagridview with combobbox without query and with invisible column in vb.net

How to filter datagridview with combobbox without query and with invisible column in vb.net?
and is it possible to be only distinct or unique value?
I want filter in "SHI" column.
Note : I use visual studio 2010
Thanks
roy
Private Sub DataGridView()
Try
dt = New DataTable
Dim query = "select ITM,ITC,QOH,PRS,PRSOBBRT,PRSOBNET,SHI,FILENAME1,FILENAME2,FILENAME3,FILENAME4,FILENAME5,FILENAME6 FROM IFG WHERE QOH > 0"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using adapter As New OleDbDataAdapter(cmd)
adapter.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
For x As Integer = 7 To 12
Me.DataGridView1.Columns(x).Visible = False
Next
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
'cn.Dispose()
End Try
End Sub

"System.OutOfMemoryException: 'Out of memory.'" when reading image from SQL Server

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.

Search function in a VB.Net windows form using sqlite

I've been having some trouble trying to get this to work, I am trying to enter a code in the top bar, press 'Go' and it show up in the ListBox on the left. I hope one of you can help me with this, I have attached the code below for entering data from the table 'stock' from my database into the list box, however I'm stuck with narrowing it down with a search function. I have also attached an image of my form.
https://i.stack.imgur.com/zD9EZ.png
Private Sub LoadStockFromDb()
Dim stockInfo As DataRow = Nothing
Dim sql As String = "SELECT * FROM stock;"
Try
Dim current_index As Int16 = lb_stock.SelectedIndex
Using conn As New SQLiteConnection(connectionString.ToString)
Using cmd As New SQLiteCommand(conn)
cmd.CommandText = sql
conn.Open()
Using da As New SQLiteDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count > 0 Then
lb_stock.DisplayMember = "int_code"
lb_stock.ValueMember = "entry_id"
lb_stock.DataSource = dt
End If
End Using
End Using
End Using
If current_index > 0 Then
lb_stock.SelectedIndex = current_index
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Direct Cast giving null error for datagridview

I am currently working in VB.NET express for desktop, 2013. I am having a hard time binding SQL data to some datagridviews on a loop with an array. I am receiving an object null error and its because on the direct cast line its not pulling the datagridview. I have multiple datagridviews on a tab control tool, one datagridview per tab. Here is my code:
try
Dim array() As Integer = {"2", "3", "4", "7", "8", "10", "11", "12"}
For Each value As Integer In array
Dim RelativeDGV = DirectCast(Me.Controls("DataGridLine" & value), DataGridView)
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT LineNumber FROM tableA where LineNumber = #LineNumber", conn1)
comm1.Parameters.AddWithValue("#LineNumber", value)
Dim dt As New DataTable
Dim sql As New SqlDataAdapter(comm1)
sql.Fill(dt)
RelativeDGV.DataSource = dt
End Using
conn1.Close()
End Using
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
The error is on line
Dim RelativeDGV = DirectCast(Me.Controls("DataGridLine" & value), DataGridView)
But the null error dosen't trigger until
RelativeDGV.DataSource = dt
Try to use list of DataGridView like this :
Try
Dim array() As DataGridView = {DataGridLine2, DataGridLine3, DataGridLine4, DataGridLine7, DataGridLine8, DataGridLine10, DataGridLine11, DataGridLine12}
For Each RelativeDGV As DataGridView In array
Dim value As Integer = Regex.Replace(RelativeDGV.Name, "[^0-9]+", String.Empty)
'or like this
'Dim value As Integer = RelativeDGV.Name.Substring(12, RelativeDGV.Name.Length - 12)
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT LineNumber FROM tableA where LineNumber = #LineNumber", conn1)
comm1.Parameters.AddWithValue("#LineNumber", value)
Dim dt As New DataTable
Dim sql As New SqlDataAdapter(comm1)
sql.Fill(dt)
RelativeDGV.DataSource = dt
End Using
conn1.Close()
End Using
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
If the various DGV controls are on other tabs, they wont be in Me.Controls. Rather than fish them out and cast them, you can iterate an array of them since you know the name. You also do not need to create a new connection for each nor duplicate datatables for each:
Dim dgvCtrls As DataGridView() = {DataGridLine2, DataGridLine3, DataGridLine4}
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT LineNumber FROM...", conn1)
' ...
dt.Load(comm1.ExecuteReader())
End Using
conn1.Close()
End Using
For Each dgv In dgvCtrls
dgv.DataSource = dt
Next
You'd only need 8 identical DataTables if you dont want each grid to automatically reflect changes made in the others. For that, use a dataset on the same connection to create the tables:
Dim SQL = "..."
Dim dgvCtrls As DataGridView() = {dgv5, dgv2, dgv3,...}
Dim ds = New DataSet
Using dbcon As New SqlConnection(SQLConnStr)
Using cmd As New SqlCommand(SQL, dbcon)
dbcon.Open()
For n As Int32 = 0 To dgvCtrls.Count - 1
ds.Load(cmd.ExecuteReader, LoadOption.OverwriteChanges, dgvCtrls(n).Name)
Next
End Using
End Using
For Each dgv In dgvCtrls
dgv.DataSource = ds.Tables(dgv.Name)
Next

Graph Not Drawing Values vb.net

dtTest.Columns.Add("TestName", GetType(String))
dtTest.Columns.Add("Score", GetType(Integer))
Dim cn As New OleDbConnection(connectionString)
cn.Open()
Dim cmd As New OleDbCommand("SELECT * From ScoreDB WHERE StudentName='" & SelectStudent.Text & "'", cn)
cmd.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While (reader.Read())
Dim TestName As String = Convert.ToString(reader("TestName"))
Dim TestScore As String = Convert.ToString(reader("ScorePercentage"))
GraphValues.Add(TestName, TestScore)
End While
Dim point As KeyValuePair(Of String, Integer)
For Each point In GraphValues
dtTest.Rows.Add(point.Key)
dtTest.Rows.Add(point.Value)
MsgBox(point.Key)
Next
With Chart1.ChartAreas(0)
.AxisX.Minimum = 0
.AxisX.Maximum = 10
.AxisY.Minimum = 0
.AxisY.Maximum = 100
.AxisY.Interval = 10
.AxisX.Title = "Test"
.AxisY.Title = "Score Percentage"
End With
cn.Close()
End Sub
I've created a form that should output a the score and test name into a column chart in vb.net, It loads all the data from the database successfully but it fails to write it to the graph and ends up just like this
any help would be appreciated as I am really struggling with this at the moment and have searched various resources such as MSDN.
Nothing is telling the chart to map the datatable GraphValues to the chart. Try something like below. You may to tinker around with the code slightly
Chart1.DataSource = GraphValues
Chart1.Series(0).XValueMember = "TestName"
Chart1.Series(0).YValueMembers = "Score"
'Data bind to the selected data source
Chart1.DataBind()
http://blogs.msdn.com/b/alexgor/archive/2009/02/21/data-binding-ms-chart-control.aspx

Resources