Combo Box Declaration expected - vb.net

When I got the value for the combo box from the MySQL database it seems getting error declaration expected in line 4. Can anyone help me? Here I attach my code
Imports MySql.Data.MySqlClient
Public Class Utama
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Me.Hide()
Dim utama As New Login
utama.Show()
End Sub
Private Sub KeluarToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles KeluarToolStripMenuItem.Click
Me.Close()
End Sub
Private Sub SupplierToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SupplierToolStripMenuItem.Click
Me.Hide()
Dim supplier As New Supplier
supplier.Show()
End Sub
Private Sub ProdukToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ProdukToolStripMenuItem.Click
Me.Hide()
Dim Produk As New Produk
Produk.Show()
End Sub
Private Sub CetakToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CetakToolStripMenuItem.Click
Me.Hide()
Dim Cetak As New Cetak
Cetak.Show()
End Sub
Dim connection As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Dim da As New MySqlDataAdapter("select * from supplier", connection)
Dim dt As DataTable
da.fill(dt)
ComboBox1.Datasource=dt
ComboBox1.DisplayMember = "npwp"
ComboBox1.ValueMember = "npwp"
End Class

You need to put that code inside a method. You can't just put arbitrary code anywhere in a class. The only thing that can be directly in the class is a declaration. The first three lines are declarations, so they're OK. The last four lines are not. That code should be inside a method somewhere. If you want to execute that code when the form loads then it should be in the Load event handler. This is pretty elementary stuff that any beginners tutorial would cover, so maybe you should work your way through such a tutorial.

First, create a method as shown below and check the exception.
Private Sub Utama_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim connection As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Dim da As New MySqlDataAdapter("select * from supplier", connection)
Dim dt As new DataTable
da.fill(dt)
ComboBox1.Datasource = dt
ComboBox1.DisplayMember = "npwp"
ComboBox1.ValueMember = "npwp"
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

Related

System.Data.OleDb.OleDbException: 'Syntax error in FROM clause.'

It keeps telling me syntax error in FROM clause. Any thought on fixing this code? I followed the tutorial 100%, somehow this error keeps happen. Also I'm using VS2019 and Microsoft Access 365. This is visual basic .net form.
Public Class Form1
Dim cmdlog As OleDbCommand
Dim drlog As OleDbDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs) Handles Clear.Click
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Btn_Login_Click(sender As Object, e As EventArgs) Handles Btn_Login.Click
Dim conn As New OleDbConnection("Provider= Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\Jane\Documents\MYSJ GA\MySJ GA\bin\Debug\Mysejahtera1.accdb")
Dim cmdlog As OleDbCommand = New OleDbCommand("Select * from user log in where [user_ID]='" & textBoxuser.Text & "' and [user_pw]='" & textBoxpw.Text & "'", conn)
conn.Open()
Dim drlog As OleDbDataReader = cmdlog.ExecuteReader
If drlog.Read() = True Then
Me.Hide()
Form4.Show()
MsgBox("login successfully")
Else
MsgBox("login failed")
End If
End Sub
End Class
I think you should use square brackets in table name:
"Select * from [user log in] where [user_ID]='"

Saving and reading files on Visual basic

Hi I'm creating a "Toilet paper tracker" on visual basic and I'm struggling with saving and reading files, I know I am missing stuff. The user should be able to login and input a threshold and when reached a warning will pop up saying "buy more toilet paper" (i haven't coded this yet) and the user can add to create a total and subtract from it too. The user should also be able to save the total to a file and I want the program to be able to read the file and change the total if the user wants to add or subtract again. It would be greatly appreciated if you pointed me in the right direction, I'm only young so it's relatively simple. Here is my program :)
Imports System.IO
Public Class frmTPT
Private Sub TPT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call loadchangetotal()
End Sub
Sub loadchangetotal()
cboChange.Items.Add("Add to Total")
cboChange.Items.Add("Subtract from Total")
End Sub
Private Sub cboVenue_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChange.SelectedIndexChanged
If cboChange.Text = "Add to Total" Then
Dim frmChangeACopy As New frmChangeA
frmChangeACopy.Show()
Me.Hide()
ElseIf cboChange.Text = "Subtract from Total" Then
Dim frmChangeSCopy As New frmChangeS
frmChangeSCopy.Show()
Me.Hide()
End If
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtThreshold.Text = ""
cboChange.Text = ""
txtTotal.Text = ""
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnReadTotal_Click(sender As Object, e As EventArgs) Handles btnReadTotal.Click
Dim FileReader As StreamReader
Dim result As DialogResult
result = OpenFileDialog1.ShowDialog
If result = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.Filename)
txtFileContent.Text = FileReader.ReadToEnd() 'i want to be able to read a
'previously saved total so that
FileReader.Close() 'it can be used to find the new total
'after it has been added to
End If 'or subtratced
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Call SaveFile()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim A, S, NewTotal As Integer
A = Val(frmChangeA.txtAdd.Text)
S = Val(frmChangeS.txtSubtract.Text)
NewTotal = A - S 'I want to be able to load a previously saved total if one exists and add and
'subtract from it
End Sub
End Class
Sub SaveFile()
Dim FileWriter As StreamWriter
Dim results As DialogResult
results = SaveFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
FileWriter.Write(txtFileContent.Text) ' is txtFileContent supposed to be
' the name of my textbox?
FileWriter.Close()
End If
End Sub
Design
You didn't mention if you were using .Net Core or 4.x. If the later, you can sometimes use the Insert Snippet functionality to learn how to do common tasks. For example in this case you could right click in the code editor and select Insert Snippet then Fundamentals then File System and finally Write text to a file. This will result in the following VB code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Unfortunately, this option doesn't work with .Net core since the My namespace wasn't ported to core.
The key point of this problem lies in reading and writing data from text. It is a clear idea to write two methods to achieve read and write.
You can refer to the following code. The two methods in the following example are WriteTotal(), ReadTotal().
Design:
Public Class Form1
Dim Oldtotal As Integer
Dim Newtotal As Integer
Private Sub btnLoadTotal_Click(sender As Object, e As EventArgs) Handles btnLoadTotal.Click
WriteTotal()
ReadTotal()
End Sub
Private Sub btnUpdateTotal_Click(sender As Object, e As EventArgs) Handles btnUpdateTotal.Click
cboChange.Text = Nothing
WriteTotal()
ReadTotal()
MsgBox("Inventory updated")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboChange.SelectedIndex = 0
ReadTotal()
End Sub
Sub WriteTotal()
Using swriter As IO.StreamWriter = New IO.StreamWriter("D:/paperstore.txt", False, System.Text.Encoding.UTF8)
If cboChange.Text = "Add to Total" Then
Newtotal = Oldtotal + CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
ElseIf cboChange.Text = "Subtract from Total" Then
If CType(txtThreshold.Text, Integer) > Oldtotal Then
swriter.WriteLine(Oldtotal)
MsgBox("buy more toilet paper")
Else
Newtotal = Oldtotal - CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
End If
Else
swriter.WriteLine(txtTotal.Text)
End If
End Using
End Sub
Sub ReadTotal()
Using sreader As IO.StreamReader = New IO.StreamReader("D:/paperstore.txt", System.Text.Encoding.UTF8)
Try
Oldtotal = sreader.ReadLine()
txtTotal.Text = Oldtotal
Catch ex As Exception
MsgBox(ex.Message)
End
End Try
End Using
End Sub
End Class

Add new row into `DataGridView` and enter data from `TableAdapter` in another form

I am trying to add new row of data in the DataGridView that is located in Form4. The data is to be entered in the Form3 into TableAdapter that is bound with DataGridView.
On the Form4 I have a button that opens Form3 and it suppose to add new rows into DatagridView but seems like it is not doing it.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Form3.Show()
Form4.DbTableDataGridView.Rows.Add() 'this is not executed?
End Sub
On the Form3 there is a TableAdapter that suppose to fill in new added rows in the DbTableDataGridView and then saves the changes. Something like:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form4.DbTableDataGridView.Rows.Add(Me.DbTableTableAdapter)
End Sub
This works fine.
Public Class Form4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form3.ShowDialog()
End Sub
End Class
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form4.DataGridView1.Rows.Add("Add Something here")
End Sub
End Class
Does the data in your datagridview is from database?
You can have a Public Sub in your Form4 to show the records.
Example:
Dim cn As New SqlConnection("your connection string here")
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Public Sub ShowRecord()
cn.Open()
With cmd
.Connection = cn
.CommandText = "Your command text here"
End With
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
dataGridView1.DataSource = dt
cn.Close()
End Sub
In your Form3:
you can save the data in the database then call the sub in form4 like
form4.ShowRecord()
This is just a simple example though

VB.NET Backgroundworker only show loading form once?

I have a button on a form which basically get data from my database as below.
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs)
Handles ToolStripButton1.Click
BackgroundWorker1.RunWorkerAsync()
Loading_Screen.ShowDialog()
End Sub
The loading screen is called after my code (obtain data from database) is run in backgroundworker.
When backgroundworker is done, I close the loading form as below
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
Handles BackgroundWorker1.RunWorkerCompleted
DataGridView1.DataSource = bSource
SDA.Update(dataTable)
ToolStripLabel1.Text = "RESULT : " + DataGridView1.RowCount.ToString
Loading_Screen.Close()
End Sub
This only works when I started the application for the first time. Whenever I click the button again, the loading form will not show anymore but the code still runs fine. Any idea?
The loading form has no code at all, just a running progress bar every time it is loaded.
What I have done but no luck :
Me.Refresh() the main form after calling loading form.
Me.Refresh() the loading form when on load function.
Tried loadingform.hide() instead of show()
Tried both show() and showdialog()
Tried creating new instance of the loading form.
Me.dispose() loading form on closing function
Me.dispose() main form on closing function
Setting loading form as top most.
UPDATE (I will keep updating my progress here)
As many of you asked to create a new instance, here is what I already did
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
BackgroundWorker1.RunWorkerAsync()
ldScreen = New Loading_Screen()
ldScreen.ShowDialog()
Me.Refresh()
End Sub
Then, in run completed,
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
DataGridView1.DataSource = bSource
SDA.Update(dataTable)
ToolStripLabel1.Text = "RESULT : " + DataGridView1.RowCount.ToString
ldScreen.Close()
BackgroundWorker1.Dispose()
End Sub
In my loading form, the code is only this
Private Sub Loading_Screen_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Me.Dispose()
End Sub
Private Sub Loading_Screen_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Refresh()
End Sub
UPDATE 2
By stripping out most of my code and putting system thread sleep in backgroundworker do work, the loading form shows up properly. So here is my code in backgroundworkerdowork on what is actually happening.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Connect2Database()
Try
sqlCommand.CommandText = "Select * from kup_table" 'Load full database into gridview
SDA.SelectCommand = sqlCommand
SDA.Fill(dataTable)
bSource.DataSource = dataTable
mySqlConn.Close()
Catch ex As MySqlException
MsgBox(ex.ToString)
If mySqlConn.State = ConnectionState.Open Then
mySqlConn.Close()
End If
Finally
mySqlConn.Dispose()
End Try
'System.Threading.Thread.Sleep(2000)
End Sub
And here is the Connect2Database function codes
Private Sub Connect2Database()
sqlCommand = New MySqlCommand
dataTable = New DataTable
SDA = New MySqlDataAdapter
bSource = New BindingSource
Try
dataTable.Clear()
mySqlConn.ConnectionString = connString
sqlCommand.Connection = mySqlConn
mySqlConn.Open()
Catch ex As MySqlException
MsgBox(ex.ToString)
If mySqlConn.State = ConnectionState.Open Then
mySqlConn.Close()
End If
End Try
End Sub
UPDATE 3
What I have noticed is that when my System.Threading.Thread.Sleep(2000) is not commented, the loading screen will show up normally. But if I changed it to System.Threading.Thread.Sleep(1), loading screen does not shows up. Why is this happening? Code runs super fast after the first time?
This is because calling Close() disposes the Form. So either you have to create a new instance of the form every time, or you need to use Hide(). Judging by your question, I think you want the former.
have you tried to create a new instance of the form?
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs)
Handles ToolStripButton1.Click
Dim frm As New Loading_Screen
BackgroundWorker1.RunWorkerAsync()
frm.ShowDialog()
End Sub

Vb.net Editing DatagridView

I created a simple program where I can search through a database table. Add data and remove data through a button. Now I want to be able to update the data within the datagrid view however i am getting the classic error: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
I have the primary key in the data grid that is not attached to anything in the vb.net program nor in the database at this time. I am not sure what I am missing.
Public Class Form1
Dim cn As New SqlConnection("Data Source=;Initial Catalog=Inventory;User ID=;Password=")
Dim adap As New SqlDataAdapter("SELECT res_snbr, First_Name, Last_Name, Item FROM Inventory_Details", cn)
Dim builder As New SqlCommandBuilder(adap)
Dim dt As New DataTable
'Dim InventoryDetailsBindingSource As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
DataGridView1.AllowUserToAddRows = True
DataGridView1.AllowUserToDeleteRows = True
DataGridView1.[ReadOnly] = False
adap.InsertCommand = builder.GetInsertCommand()
' adap.UpdateCommand = builder.GetUpdateCommand()
adap.UpdateCommand = builder.GetUpdateCommand
adap.Fill(dt)
InventoryDetailsBindingSource.DataSource = dt
DataGridView1.DataSource = InventoryDetailsBindingSource
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.TextLength > 0 Then
InventoryDetailsBindingSource.Filter = String.Format("First_Name Like '%{0}%'", TextBox1.Text)
Else
InventoryDetailsBindingSource.Filter = String.Empty
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
adap.Update(dt)
MessageBox.Show("Saved successfully")
Catch ex As Exception
MessageBox.Show("Error updating database")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
adap.Update(dt)
DataGridView1.[ReadOnly] = True
Button2.Enabled = False
End Sub
End Class
Actually I was incorrect. I did not have a primary key set on my database. I dropped my table - recreated with primary key.