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
Related
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
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 using SQL Server 2016 Visual studio 2017.
Need to fill checkedlistbox2, from my database, based on the value of the SelectedItem of Checkedlistbox1.
I am filling checkedlistbox1 on Form.Load as below:
This code is working.
Private Sub fillChkboxList()
Dim conn As New SqlConnection("Data Source=192.168.200.36;user id=sa;password=XXXX#123;database=XXXXXXX")
Dim sda As New SqlDataAdapter("select DepartmentName, DepartmentID from DepartmentMain where active=1 order by DepartmentName", conn)
Dim dt As New DataTable
sda.Fill(dt)
CheckedListBox1.DataSource = dt
CheckedListBox1.DisplayMember = "DepartmentName"
CheckedListBox1.ValueMember = "DepartmentID"
End Sub
Here I am trying to use a method to fill Checkedlistbox2, which I am calling in the ItemCheck event handler of Checkedlistbox1:
Below Code is not giving required results
Public Function fillChkboxListSub()
Dim i As Integer
Dim conn1 As New SqlConnection("Data Source=192.168.200.36;user id=sa;password=XXXX#123;database=XXXXXXX")
With CheckedListBox2
For i = 0 To CheckedListBox1.Items.Count - 1 Step i + 1
If CheckedListBox1.GetItemCheckState(i) = CheckState.Checked Then
Dim xx As String = (CType(CheckedListBox1.Items(i), DataRowView))("DepartmentID")
Dim sqlstr2 As String = "select SubName,SubDeptID from DepartmentSub where active=1 and DepartmentID in ('" & xx & "') order by SubName"
Dim command2 As New SqlCommand(sqlstr2, conn1)
Dim adpt2 As New SqlDataAdapter(command2)
adpt2.SelectCommand = command2
adpt2.Fill(dt2)
CheckedListBox2.DataSource = dt2
CheckedListBox2.DisplayMember = "SubName"
CheckedListBox2.ValueMember = "SubDeptID"
End If
Next
End With
End Function
This function I am calling on:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
fillChkboxListSub()
End Sub
I am not getting the result.
If I check the (DepartmentName) in checkedlistbox1, SubDeptName should load in checkedlistbox2. If I deselect the same in checkedlistbox1, it should be deleted or removed from checkedlistbox2Please help with working code example.
Thanks in Advance
Most database objects need to be disposed. Connections, Commands, and DataReaders have a Dispose method that must be called to release unmanaged resources that they use. It is made easy for us with Using...End Using blocks that ensure that Dispose is called even if there is an error.
The order of setting the DataSource, DisplayMember, and ValueMember is important. Setting DataSource should be last line. If you set ValueMember before DataSource no action is triggered. If you set Datasource first, the box will bind value member for you. Then, you're going to set a new ValueMember (the one you want) and box will have to re-wire binding. So, if you set DataSource last, bindings will happen only once.
You can use the CheckedItems collection to loop through. Add eacn item to a list. After the loop use Join with a comma separator to prepare the In clause for the sql string. I used an interpolated string to build the sql string indicated by the preceding $. Variables can then be inserted in line surrounded by { } .
Private CnString As String = "Data Source=192.168.200.36;user id=sa;password=XXXX#123;database=XXXXXXX"
Private Sub fillChkboxList1()
Dim dt As New DataTable
Using conn As New SqlConnection(CnString),
cmd As New SqlCommand("select DepartmentName, DepartmentID from DepartmentMain where active=1 order by DepartmentName", conn)
conn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
CheckedListBox1.DisplayMember = "DepartmentName"
CheckedListBox1.ValueMember = "DepartmentID"
CheckedListBox1.DataSource = dt
End Sub
Public Sub fillChkboxList2()
Dim lst As New List(Of Integer)
For Each item In CheckedListBox1.CheckedItems
Dim drv = DirectCast(item, DataRowView)
Dim DepId As Integer = CInt(drv("DepartmentId"))
lst.Add(DepId)
Next
Dim DepIdString = String.Join(",", lst)
Dim sql As String = $"select SubName,SubDeptID from DepartmentSub where active=1 and DepartmentID in ({DepIdString}) order by SubName"
Debug.Print(sql) 'See if your select string looks correct.
Dim dt As New DataTable
Using cn As New SqlConnection(CnString),
cmd As New SqlCommand(sql, cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
CheckedListBox2.DisplayMember = "SubName"
CheckedListBox2.ValueMember = "SubDeptID"
CheckedListBox2.DataSource = dt
End Sub
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
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