Add Items to a ListView from a database - database

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

Related

VB.NET add or subtract an integer value to a SQL Server value into a label when selecting a combobox item

Following my previous question answered by #Andrew Morton, I have one more :)
Here is my whole code (not very long for now) :
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class Form1
Sub PopulateCB()
Dim connection As String = "Data Source=.\SQLEXPRESS;Initial Catalog=OST;Integrated Security=True"
Dim sql = "SELECT * FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connection),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
ComboBoxC1L1.DataSource = dt
ComboBoxC1L1.DisplayMember = "nom_unité"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateCB()
End Sub
Private Sub ComboBoxC1L1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxC1L1.SelectedIndexChanged
Dim cb = DirectCast(sender, ComboBox)
If cb.SelectedIndex >= 0 Then
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of Integer)("cout_unité")
If ComboBoxQC1L1.Text = "ordinaire" Then
LabelPointsC1L1.Text = val
ElseIf ComboBoxQC1L1.Text = "médiocre" Then
LabelPointsC1L1.Text = val - 2
ElseIf ComboBoxQC1L1.Text = "élite" Then
LabelPointsC1L1.Text = val + 2
End If
If cb.SelectedIndex >= 0 Then
Dim val2 = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of String)("type_unité")
LabelUnitType.Text = val2
End If
End If
Try
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBoxQC1L1.Text = "ordinaire"
End Sub
Private Sub TextBoxC1L1_TextChanged(sender As Object, e As EventArgs) Handles TextBoxC1L1.TextChanged
Try
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1
Catch ex As exception
End Try
End Sub
End Class
Here is the program interface
Here is the SQL table look
Here is the program interface when the Button has been clicked
Red Arrow ComboBox text is a DropDownStyle box with 3 possible text choices:
ordinaire,
élite,
médiocre
What I want to do: when changing the red arrow combobox text, the cout_unité label should change too with a "cout_unité -2" in case of "médiocre" ComboBox text, or "cout_unité +2" in case of "élite" ComboBox text or remain = to "cout_unité" if the selected text is "ordinaire".
And it should calculate this only once from the original "cout_unité" value in the table (in case of clicking 10 times on "ordinaire", it shouldn't subtract 10 * 2 to the "cout_unité" value, only 1 * 2)
I can do it in the ComboBoxC1L1 (see code) but I can't reproduce it with this red arrow combobox (probably because of the type of data into this combobox which are "strings", I don't know).
Many thanks :)
Since there is only a single Handles clause, the following line is unnecessary. The sender can only be the ComboBox in the Handles.
Dim cb = DirectCast(sender, ComboBox)
If you set the ValueMember of the combo in the PopulateCB method, you can save a long line of code making the code more readable.
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of Integer)("cout_unité")
To:
Dim val = CInt(ComboBoxC1L1.SelectedValue)
We need the CInt since SelectedValue is an Object.
Don't assign the DataSource until after the DisplayMember and ValueMember are set.
You are checking twice for ComboBoxC1L1.SelectedIndex >= 0.
Just include the unit type in the first If.
The user may not have to trigger the SelectedIndexChanged event if the correct value is already selected. Maybe a button click would be better.
Sub PopulateCB()
Dim connection As String = "Data Source=.\SQLEXPRESS;Initial Catalog=OST;Integrated Security=True"
Dim sql = "SELECT * FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connection),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
ComboBoxC1L1.DisplayMember = "nom_unité"
ComboBoxC1L1.ValueMember = "cout_unité"
ComboBoxC1L1.DataSource = dt
End Sub
Private Sub btnCalculateValue_Click(sender As Object, e As EventArgs) Handles btnCalculateValue.Click
If ComboBoxC1L1.SelectedIndex >= 0 Then
Dim val = CInt(ComboBoxC1L1.SelectedValue)
If ComboBoxQC1L1.Text = "ordinaire" Then
LabelPointsC1L1.Text = val.ToString
ElseIf ComboBoxQC1L1.Text = "médiocre" Then
LabelPointsC1L1.Text = (val - 2).ToString
ElseIf ComboBoxQC1L1.Text = "élite" Then
LabelPointsC1L1.Text = (val + 2).ToString
End If
Dim val2 = DirectCast(ComboBoxC1L1.SelectedItem, DataRowView).Row.Field(Of String)("type_unité")
LabelUnitType.Text = val2
End If
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1.ToString
End Sub

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.)

How to update/modify an existing row in an Access Database using Visual Basic

I am having difficulty updating an existing row in an Access Database using VB. I want to be able to make changes to fields in an already populated existing row in my access table.
The code I have relates to adding a new record at the bottom of the table rather than the above.
Public Class Form1
Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = StudentDatabase.accdb")
Dim objStudentDA As New OleDb.OleDbDataAdapter("Select * FROM Student", objConnection)
Dim objStudentCB As New OleDb.OleDbCommandBuilder(objStudentDA)
Dim objDs As New DataSet()
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
If txtStudentNum.Text <> "" And txtSurname.Text <> "" And txtAttendance.Text <> "" And txtCA1.Text <> "" And txtCA2.Text <> "" And txtFinalExamResult.Text <> "" Then
Dim objRow3 = objDs.Tables("Student").Rows.Find(txtUpdateStudentID.Text.ToString)
'Editing each field value based on textboxes
objRow3.Item("FName") = txtUpdateFName.Text
objRow3.Item("SName") = txtUpdateSName.Text
objRow3.Item("Attendance") = txtUpdateAttendance.Text
objRow3.Item("CA1") = txtUpdateCA1.Text
objRow3.Item("CA2") = txtUpdateCA2.Text
objRow3.Item("FinalExam") = txtUpdateFinalExam.Text
objRow3.Item("OverallResult") = txtUpdateOverallGrade.Text
**'ERROR HERE STATING THIS ROW ALREADY BELONGS TO A TABLE**
objDs.Tables("Student").Rows.Add(objRow3)
objStudentDA.Update(objDs, "Student")
MsgBox("Record has been added to the IS2215 Database!")
Retrieve()
Else
MsgBox("Error: You must not leave any fields blank!")
End If
End Sub
Public Sub Retrieve()
objDs.Clear()
objStudentDA.FillSchema(objDs, SchemaType.Source, "Student")
objStudentDA.Fill(objDs, "Student")
cmbStudentFind.Items.Clear()
Dim i As Integer, strCurrentID As String
For i = 1 To objDs.Tables("Student").Rows.Count
strCurrentID = objDs.Tables("Student").Rows(i - 1).Item("ID")
cmbStudentFind.Items.Add(strCurrentID)
cmbUpdateStudentID.Items.Add(strCurrentID)
Next
cmbStudentFind.SelectedIndex = 0
cmbUpdateStudentID.SelectedIndex = 0
FillUpdateDetails()
End Sub
Public Sub FillUpdateDetails()
Dim objRow2 As DataRow
objRow2 = objDs.Tables("Student").Rows.Find(cmbUpdateStudentID.SelectedItem.ToString)
txtUpdateStudentID.Text = objRow2.Item("ID")
txtUpdateFName.Text = objRow2.Item("FName")
txtUpdateSName.Text = objRow2.Item("SName")
txtUpdateAttendance.Text = objRow2.Item("Attendance")
txtUpdateCA1.Text = objRow2.Item("CA1")
txtUpdateCA2.Text = objRow2.Item("CA2")
txtUpdateFinalExam.Text = objRow2.Item("FinalExam")
txtUpdateOverallGrade.Text = objRow2.Item("OverallResult")
End Sub
End Class
You need to execute CRUD against your Database. You will have a lot of problems trying to perform those operations against Access, as it tends to lock Tables when a Table is being accessed.
I would suggest you build a CRUD framework to "machine gun" the Insert, Update, and/or Delete operations into Access as you need.
Outside of that, you will loose a lot of hair in the process of trying to make it work.
For making inserts, you can stick with your current TextBox setup. For making updates, I would think a DataGridView would be a better way to go.
Something like this should work for you.
Imports System.Data.OleDb
Public Class Form1
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim oledbCmdBuilder As OleDbCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim i As Integer
Dim sql As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
connection = New OleDbConnection(connetionString)
Sql = "select * from tblUsers"
Try
connection.Open()
oledbAdapter = New OleDbDataAdapter(Sql, connection)
oledbAdapter.Fill(ds)
DataGridView1.Data Source= ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
oledbAdapter.Update(ds.Tables(0))
End If
ds.AcceptChanges()
MsgBox("Save changes")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Or, you can stick with the TextBox concept, and change your setup slightly, as such.
str = "Journals SET JournalTitle=?, JournalText=? WHERE JournalDate=?"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#jounalTitle", MyJournalTitle )
cmd.Parameters.AddWithValue("#journalText", MyJournalText)
cmd.Parameters.AddWithValue("#journalDate", DatePicked)
cmd.ExecuteNonQuery()
That methodology is much safer than the way you are doing it now. There are more details here.
How to update MS Access Database (vb.net)

How to calculate the sum of Row values in a specific column in a datagridview in vb.net

How do i calculate the sum of datagridview row content from a specific column?
Suppose, this is my datagridview;
Name Score
John 35
Helen 34
James 30
Total 99
I want to calculate the sum of column "score" put it in the textbox.
Thanks for the help.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim i,total As Integer
total = 0
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Try
connection.Open()
adapter.SelectCommand = New SqlCommand("SELECT * FROM your_DB_table", connection)
adapter.Fill(ds)
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
total = total + ds.Tables(0).Rows(i).Item(1)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
textbox1.text = total
End Sub
End Class
I think this will help you.
Something like this,
Dim sumOfScore As Integer = 0
For Each row As DataRow in *yourDataRow*
Dim score As Integer = CInt(row.Item("Score").ToString())
sumOfScore += score
Next
txtYourTextBox.Text = sumOfScore.ToString
I also got this code which solves my problem:
Private Sub GetSUMofUnits()
Dim total As Integer
For Each row As DataGridViewRow In dgvSubjectsEnrolled.Rows
total += row.Cells(4).Value
Next
txtUnits.Text = total
End Sub

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

Resources