Listbox into an Access DB - database

So far I have this, which doesn't work. I think I'm off on the wrong path here. Basically I'm trying to transfer all of the items of a list box to separate columns of an Access DB named CalcOps, with the columns of "NumOne, Operator, NumTwo, Result). The list box can currently have 10 total list items, all of which should be transferred when the button is clicked (ButtonDBSave). The list box items are put together from separate text boxes and the operator that is clicked on is transferred to the list box via Listbox.tag. Not getting any errors...or anything else.
Private Sub ButtonDBSave_Click(sender As Object, e As EventArgs) Handles ButtonDBSave.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0"
dbSource = "Data Source=|DataDirectory|\CalcDB.accdb"
con.ConnectionString = dbProvider & dbSource
Dim arr As New List(Of String)
Dim cmdText As String = "INSERT INTO NumOne ()"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(cmdText)
cmd.CommandType = CommandType.Text
con.Open()
With cmd.Parameters
.Add("#NumOne", OleDb.OleDbType.VarChar).Value = NumOne.Text
End With
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.)

Filling multi tables into dataset?

I have problem with my code which fills multi tables into my dataset. It loads all contents contained in tables of my database to only one table in dataset. My code is shown below. How to load those tables from database into a dataset , that has the same number of tables and contents.
Private Sub Filldataset()
Private cnn As OleDbConnection
Private dt As New DataTable
Private da As New OleDbDataAdapter
Private cmd As New OleDbCommand
Private ds As New DataSet
Dim tblrestrictions As String() = New String() {Nothing, Nothing, Nothing, "TABLE"}
Dim userTables As DataTable = Nothing
userTables = cnn.GetSchema("Tables", tblrestrictions)
Dim i As Integer
For i = 1 To userTables.Rows.Count - 1 Step 1
cnn = New OleDbConnection(Str)
cnn.Open()
cmd = cnn.CreateCommand
cmd.CommandText = "select * from" & " " & userTables.Rows(i)(2).ToString
dt.Clear()
da.SelectCommand = cmd
da.Fill(dt)
da.Fill(ds)
Next
cnn.Close()
MessageBox.Show(ds.Tables.Count)
End Sub
Connections can be created elsewhere but should not be opened or closed until directly before an directly after you use them. You will have to adjust this code for an Oledb application.
Private Sub GetData()
cn.Open()
Dim dt As DataTable = cn.GetSchema("Tables")
cn.Close()
Dim ds As New DataSet
Dim row As DataRow
For Each row In dt.Rows
Dim strTableName As String = row(2).ToString
Dim strSQL As String = "Select * From " & strTableName
Dim cmd As New SqlCommand(strSQL, cn)
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
da.Fill(ds, strTableName)
Next
Debug.Print(ds.Tables.Count.ToString)
End Sub
I scoped several variables locally that you will want to scope to the class like the dataset

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

error deleting from database

I have a SQL Server Compact database created through VS 2010 (Local Database File option).
On form load (CategoryForm) I load the values from the database into the DataGridView1. I also add an extra ButtonColumn programmatically that I use for the Delete part.
The problem is this:
On initial form load, the first time I press delete on any row, it works. If i press it again it does not work.
The second time i click the button, the printed text I get on my Msgbox, is the Text of button! (delete) (screenshot included) p.s As mentionted below, when I comment-out the extra stuff, I get the correct values returned.
What I tried:
Commented out everything SQL-related, left only the part where I get the RowIndex and the value at the specific cell at that index. I print them both on MsgBox. The values I get are correct. For example, 0 index and value test for first row with text test.
Below is my progress as well as screenshots:
CellContentClick method:
Private Sub DataGridView1_CellContectClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim i As String
'If e.ColumnIndex = 1 Then
'If e.RowIndex >= 0 And e.RowIndex <= DataGridView1.Rows.Count - 1 Then
i = DataGridView1.Rows(e.RowIndex).Cells(0).Value.ToString
MsgBox(e.RowIndex)
MsgBox(i)
SQLStringDelete = "DELETE FROM Category WHERE categoryname = '" & i & "'"
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open() 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStringDelete 'Sets the SQL String
SQLCmd.ExecuteNonQuery() 'Executes SQL Command
'Create Adapter
Dim DataAdapter As SqlCeDataAdapter = New SqlCeDataAdapter("SELECT categoryname FROM Category", SQLConn)
'Create DataSet
Dim Dataset As New DataSet
'fill the datset
DataAdapter.Fill(Dataset)
'attach dataset to the datagrid
With DataGridView1
.DataSource = Dataset.Tables(0)
.Columns(0).HeaderText = ""
.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
DataAdapter = Nothing
Dataset = Nothing
SQLConn.Close() 'Close the connection
End Sub
Form_Load method:
Private Sub CategoryForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open() 'Open the connection
'Create Adapter
Dim DataAdapter As SqlCeDataAdapter = New SqlCeDataAdapter("SELECT categoryname FROM Category", SQLConn)
'Create DataSet
Dim Dataset As New DataSet
'fill the datset
DataAdapter.Fill(Dataset)
'attach dataset to the datagrid
With DataGridView1
.DataSource = Dataset.Tables(0)
.Columns(0).HeaderText = ""
.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
DataAdapter = Nothing
Dataset = Nothing
SQLConn.Close()
With buttonColumn
.Name = "DeleteButtonColumn"
.HeaderText = ""
.Text = "Delete"
.UseColumnTextForButtonValue = True
.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
.Width = 50
End With
If DataGridView1.Columns.Count = 1 Then
DataGridView1.Columns.Add(buttonColumn)
End If
End Sub
Screenshots:
Turns out that the columns where autoregenerating causing column re-arrangement on each the second click. Just set DataGridView1.AutoGenerateColumns = false in both the form load and event and it works.

binding muliple data from sql to label by choosing item in combobox

how i bind multiple data from sql to label if i choose an item in combo box that is from sql this is my code:
Private Sub cmboCourse_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmboCourse.SelectedIndexChanged
If cmboCourse.Text = "ADVANCED COMPUTER TECHNICIAN" Then
callMe()
ElseIf cmboCourse.Text = "AUTOELECTRICITY" Then
callMe()
ElseIf cmboCourse.Text = "AUTOMOTIVE" Then
callMe()
End If
End Sub
Private Sub callMe()
Dim str As String = ("Data Source=PC1; User ID=sa; Password=pwd;Databasfriend")
Dim con As New SqlConnection(str)
Dim str1 As String = "SELECT * FROM tbl_course"
Dim da As New SqlDataAdapter(str1, con)
Dim dataset1 As New DataSet()
da.Fill(dataset1, "course")
lbl.DataBindings.Add("text", dataset1, "course.Course_Code")
end sub
and this is my table
Course_Code Course
ACT ADVANCED COMPUTER TECHNICIAN
AE AUTOELECTRICITY
AM AUTOMOTIVE
it binds only one data, i want to bind many data in a particular column example i choose a course AUTOMOTIVE in combo box how does course_code of AUTOMOTIVE binds to label and if i choose AUTOELECTRICITY how does course_code of AUTOELECTRICITY binds to the same label
This is not tested, let me know if it doesn't work.
Private Sub cmboCourse_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmboCourse.SelectedIndexChanged
callMe(cmboCourse.Text)
End Sub
Private Sub callMe(ByVal course as String)
Dim str As String = ("Data Source=PC1; User ID=sa; Password=pwd;Databasfriend")
Dim con As New SqlConnection(str)
Dim str1 As String = "SELECT * FROM tbl_course WHERE [Course]='" & course & "'"
Dim da As New SqlDataAdapter(str1, con)
Dim dataset1 As New DataSet()
da.Fill(dataset1, "tbl_course")
'lbl.DataBindings.Add("text", dataset1, "course.Course_Code")
If dataset1.Tables("tbl_course").Rows.Count > 0 Then
lbl.Text = dataset1.Tables("tbl_course").Rows(0)("Course_Code")
Else
MsgBox "Course [" & course & "] not found"
End If
End Sub
Please note that in your code, da.Fill(dataset1, "course") you specify the table to be 'course', while the select statement selects from 'tbl_course' table. I am assuming the latter is correct name.
Edit 1:
Bug fix
Edit 2:
Debugging
sc.Open()
Dim da As New SqlDataAdapter()
Dim dataset1 As New DataSet()
Dim sql As New SqlCommand("Select * from book where Title='" + cmbtit.Text + "'", sc)
da.SelectCommand = sql
da.SelectCommand.ExecuteNonQuery()
da.Fill(dataset1, "book")
If dataset1.Tables("book").Rows.Count > 0 Then
txtauthor.Text = dataset1.Tables("book").Rows(0)("Author")
Else
MsgBox("Author [" & cmbtit.Text & "] not found")
End If
sc.Close()
End Sub

Resources