Using ValueMember for a combobox or a Listbox - sql-server

I have created a table in SQL Server :
its name is [dbo].[Family_Tree]
ID NodeName
1 John
2 George
3 Mike
4 Sandra
5 Jasmine
6 Lucy
I have created a Vb.net Application where I want to present these names in a Combobox or a listbox
Here's the code to fill the Listbox:
Using con As New SqlConnection(My.Settings.ConnString)
Dim DT As New DataTable
Dim Adp As New SqlDataAdapter
With Adp
.SelectCommand = New SqlCommand("Select NodeName , ID From Family_tree", conn)
.Fill(DT)
End With
With ListBox1
.DataSource = DT
.DisplayMember = "NodeName"
.ValueMember = "ID"
End With
End Using
Names are Displayed and nothing is wrong with them , what I want is when I choose any name the listbox returns its corresponding ID .ValueMember = "ID"
, I tested it in a msgbox MsgBox(ListBox1.ValueMember) it always Returns ID , so how can I make it understand that this is a Column not a String ?
thanks in advance...

To get the Value of the current displayed item in the listbox you write
if ListBox1.SelectedValue IsNot Nothing Then
Dim v = Convert.ToInt32(ListBox1.SelectedValue)
.......
ListControl.SelectedValue
Gets or sets the value of the member property specified by the
ValueMember property.

You could use ListBox.SelectedItem, f.e. in it's SelectedIndexChanged event:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim curItem As DataRowView = TryCast(ListBox1.SelectedItem, DataRowView)
If curItem IsNot Nothing Then
Dim id = curItem.Row.Field(Of Int32)("ID")
End If
End Sub

Related

VB.NET synchronized Combobox and label from SQL Server

I'm trying to synchronize the reading of a SQL Server table with 2 columns (nom_unité and cout_unité).
The first column (nom_unité) will be populated into a combobox and I want the second column (cout_unité) to be synchronized into a label with the first combobox (meaning, when I change the combobox value, the label should change too refering to the table).
I can do this with 2 comboboxes :
Dim connection As New SqlConnection("Data Source=xxx")
Dim dt As New DataTable
Dim sqlquery As String
connection.Open()
sqlquery = "select * from liste_unités"
Dim SQL As New SqlDataAdapter(sqlquery, connection)
SQL.Fill(dt)
Dim cmd As New SqlCommand(sqlquery, connection)
ComboBoxC1L1.DataSource = dt
ComboBoxC1L1.DisplayMember = "nom_unité"
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "cout_unité"
but I do not know how to do it with a label (instead of ComboBox1).
I believe I can achieve it with something like that :
Dim sqlcmd As New SqlCommand("select * from liste_unités", connection)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
Label1.Text = myreader.Item("cout_unité").ToString
End If
but this is only reading the first row and not changing the label value when changing the first combobox selected value.
How to do it the easiest and most efficient way ?
Thank you :)
As you have assigned the datasource of the combobox to a datatable which contains the information you need, you can get that information when the value of the combobox changes.
I started a new Windows Forms project and put a combobox (named "cbNomUnité") and a label (named "lblCoutUnité") on Form1 and used this code:
Imports System.Data.SqlClient
Public Class Form1
Dim connStr As String = "Server=.\SQLEXPRESS;Database=Testing;Trusted_Connection=true;"
Sub PopulateCB()
Dim sql = "SELECT nom_unité, cout_unité FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connStr),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
cbNomUnité.DataSource = dt
cbNomUnité.DisplayMember = "nom_unité"
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbNomUnité.SelectedIndexChanged
Dim cb = DirectCast(sender, ComboBox)
If cb.SelectedIndex >= 0 Then
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of String)("cout_unité")
lblCoutUnité.Text = val
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PopulateCB()
End Sub
End Class
To get a program that does this:
(Refresh the page to see the animation again.)

Fill a CheckedListbox from a database based on checked values of another CheckedListbox

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

How to do a search-as-you-type textbox in a DataGridView using VB.NET

I have connected my DataGridView to a database but I can't implement the search function.
The flow of the program would be when I click one column of the DataGridView and I type in the search box, I can only get results from that same column not the other columns beside it.
It should also search letter by letter so basically a TextChanged event.
This is how i would do it
First, to have two variable to store your original datatable from database, and also a string variable to store your selected dgv column headertext (which will be used to do the filter later on).
Private oriDataTable As New DataTable
Private columnToFilter As String = String.Empty
My test on some dummy data
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'dummy datatable
oriDataTable.Columns.Add(New DataColumn("ID"))
oriDataTable.Columns.Add(New DataColumn("FirstName"))
oriDataTable.Columns.Add(New DataColumn("LastName"))
For i = 0 To 5
Dim dr As DataRow = oriDataTable.NewRow()
dr.Item("ID") = i
dr.Item("FirstName") = "fn type1 " & i
dr.Item("LastName") = "ln type1 " & i
oriDataTable.Rows.Add(dr)
Next
For i = 6 To 10
Dim dr As DataRow = oriDataTable.NewRow()
dr.Item("ID") = i
dr.Item("FirstName") = "fn type2" & i
dr.Item("LastName") = "ln type2" & i
oriDataTable.Rows.Add(dr)
Next
'Since you already connected to database
'i assume that you could fill a datatable and bind to dgv
dgvToFilter.DataSource = oriDataTable
columnToFilter = "ID" 'Assign any default column name
End Sub
Then add a ColumnHeaderMouseClick event handler on your dgv, update the columnToFilter each time when user click on it.
Private Sub dgvToFilter_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvToFilter.ColumnHeaderMouseClick
Dim clickedColumn As DataGridViewColumn = dgvToFilter.Columns(e.ColumnIndex)
'Note:HeaderText must match with your datatable column name
columnToFilter = clickedColumn.HeaderText
lblHeaderSelected.Text = columnToFilter
End Sub
And lastly the TextChaged Event. Use the DataTable.Select method to filter the datatable and update the result, if any, to the dgv.
Private Sub txtFilterText_TextChanged(sender As Object, e As EventArgs) Handles txtFilterText.TextChanged
If txtFilterText.Text.Length <= 0 Then dgvToFilter.DataSource = oriDataTable
Dim filterString = String.Format("{0} LIKE '{1}%'", columnToFilter, txtFilterText.Text)
Dim dataRows As DataRow() = oriDataTable.Select(filterString)
'Choose what you wan to do if no row is found. I bind back the oriDataTable.
dgvToFilter.DataSource = If(dataRows.Count > 0, dataRows.CopyToDataTable(), oriDataTable)
End Sub
You can try this.
Private Sub txtUname_TextChanged(sender As Object, e As EventArgs) Handles txtUname.TextChanged
dtaAdap = New SqlDataAdapter("Select * from tbl_user where Fname like '%" & txtUname.Text & "%'" & vbCrLf &
" OR Lname like '%" & txtUname.Text & "%'", con)
dt = New DataTable
dtaAdap.Fill(dt)
DataGridView1.DataSource = dt
End Sub
The query in SQLAdapter goes a little something like this:
Select * from <tbl_name> where <firstparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'
OR <secondparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'
and so on depending on the number of fields you want to look at. Note: "con" is my SQLConnection.
This whole code snippet will fill your DatagridView with the result of the query everytime the user key in something on your searchtextbox.

VB.NET listview not showing all data from dataset

This issue is driving me mad, I can't work out why it's happening. I'm running a query in an access db using vb.net then putting the data into a listview. Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strAccessConn As String = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = T:\mydb.accdb"
Dim cn As OleDbConnection = New OleDbConnection(strAccessConn)
Dim ds As New DataSet
Dim dt As DataTable
'Note the query is entered as a string.
Dim da As New OleDbDataAdapter("Q_LIST", cn) 'is the name of the query in Access
'Set the CommandType of the SelectCommand to TableDirect
da.SelectCommand.CommandType = CommandType.TableDirect
da.Fill(ds, "mytable")
dt = ds.Tables("mytable")
ListViewBatchResults.MultiSelect = True
ListViewBatchResults.View = View.Details
ListViewBatchResults.GridLines = True
ListViewBatchResults.Columns.Clear()
ListViewBatchResults.Items.Clear()
For Each col As DataColumn In dt.Columns()
ListViewBatchResults.Columns.Add(col.ToString)
Next
MsgBox(dt.Rows.Count)
For Each row As DataRow In dt.Rows()
Dim lst As ListViewItem
lst = ListViewBatchResults.Items.Add(row(0))
For i As Integer = 1 To dt.Columns.Count - 1
lst.SubItems.Add(row(i))
Next
Next
End Sub
This listview is not showing all the returned data though, and I can't work out why - it works on other queries in the DB but not this one for some reason. The row count shows that there are 264 rows, the listview only shows 3 of them when I run the project however. What the heck is going on?
Cheers!
Dim lst As ListViewItem
to
Dim lst As New ListViewItem

datagridview to textbox binding data

When the program is executed, the datagridview populate data and also the textboxes(example StockNumber,Description) and when i typed words in the search textbox ,the datagridview filters the matching words.When I clicked the item in the datagridview the textboxes does not changed it didnt show the information...
what the solution for my problem..i need to display the information in the textboxes when i clicked the item in the datagridview..
Private Sub txtreg_delsrch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtreg_delsrch.TextChanged
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\sony\Documents\Visual Studio 2008\Projects\Inventory\ItemInventory.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT StockNo,Item,Description,Reference,Quantity,Unit FROM Supplies_Regular WHERE Description Like '%" & txtreg_delsrch.Text & "%'", con)
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "MyTable")
Supplies_RegularDataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
End Sub
Perhaps you could use BindingSource:
Dim binding = New BindingSource()
With { .DataSource = myDataSet.Tables("MyTable") }
Supplies_RegularDataGridView1.DataSource = binding
StockNumber_textBox1.DataBindings.Add("Text", binding, "StockNo")
Last line simply binds your object's StockNo property to TextBox.Text.
You could do something like this in the Grid CellClick event.
Dim row As Integer = e.RowIndex
Dim col As Integer = e.ColumnIndex
textbox.Text = grid.Item(col, row).value

Resources