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.)
Related
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 a Vb nooby and I have trouble to add specific Items to my Listview from a database.
I would like to compare the value of a combobox with a column value of a table.
To proof if they are equal like apple = apple
When they are equal the whole data set should be added to my ListView. (Only data sets which have the equal value like the selected item of the combobox)
Please Help !!
Thanks a lot and best regards
You can try below code..
Imports System.Data.SqlClient
Public Class Form1
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
conn = New SqlConnection("Data Source=SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=id;Password=pass")
Dim strQ As String = String.Empty
strQ = "SELECT * FROM Northwind.dbo.Products"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
End Sub
End Class
You can try this link.
Thanks for your help.
In my solution, I just set a parameter into the sql statement.
Public Function getRahmenvertrag**(ByVal costumerID As Integer)** As List(Of Rahmenvertrag)
Dim sqlCom As New SqlServerCe.SqlCeCommand
sqlCom.CommandText = **"SELECT * FROM Rahmenvertrag LEFT OUTER JOIN Kunde ON Kunden_FID = Kunden_ID WHERE Kunden_ID = #Kunde "**
**sqlCom.Parameters.AddWithValue("Kunde", costumerID)**
Private Sub ComboBox1_Click(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
ListView4.DataBindings.Clear()
ListView4.Items.Clear()
If IsNothing(ComboBox1.SelectedItem) = False Then
For Each Rahmenvertrag As Rahmenvertrag In controller.getRahmenvertrag(ComboBox1.SelectedItem.kunde_ID)
With ListView4.Items.Add(Rahmenvertrag.bezeichnung)
.SubItems.Add(Rahmenvertrag.inhalt)
End With
Next
End If
End Sub
I have a form with a datagridview (ViewCustomersForm) and a save button.
What I am trying to do is get the user to edit the infotmation in the datagrid view and then hit a save button, which will save the values back to my SQL table.
Unfortunately though, when my save button is pressed I get the following error.
"Value cannot be null."
Pointing at this line of code:
dataadapter.Update(ds.Tables("Customers_table"))
In the context of the below code:
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Customers._Customers' table. You can move, or remove it, as needed.
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim ds As DataSet = New DataSet()
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
End Sub
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim ds As DataSet = New DataSet()
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
I am relatively new to VB, so any help or pointers greatly appreciated.
Thanks
I needed to have by variables defined at the Class level, not with in the Subs.
Here is the working code.
Imports System.Data.SqlClient
Imports System.Data.Common
Public Class ViewCustomersForm
Dim ds As DataSet = New DataSet()
Dim connStr As String = "server=barry-laptop\SQLEXPRESS; database=BillingReferenceData; integrated security=yes"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(Sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Private Sub Button1_Click(sender As Object, e As EventArgs)
End Sub
Private Sub ViewCustomersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'---open the connection and fill the dataset---
conn.Open()
dataadapter.Fill(ds, "Customers_table")
conn.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers_table"
End Sub
Private Sub Button_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmdBuilder As New SqlCommandBuilder(dataadapter)
sqlCmdBuilder.GetUpdateCommand()
dataadapter.Update(ds.Tables("Customers_table"))
End Sub
End Class
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
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