Can someone help me out. I have a combobox where the items are from my database. If I drop down the combobox and select an item, the datagridview must show the firstname,lastname etc. My data type at studentno is varchar, the int does not work too. The data will be get from two different table
2nd is how can I refresh the combobox? Because I need to close then reopen the program before the data that will be insert at combobox.
Private Sub ComboBox6_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox6.SelectedIndexChanged
conn.Open()
query = "select student.studentno,student.firstname,student.middlename,student.lastname,subject.subjcode,subject.subjdesc from student,subject where student.studentno = '" & ComboBox6.SelectedText & "' "
cmd = New MySqlCommand(query, conn)
da.SelectCommand = cmd
ds = New DataSet
da.Fill(ds, "ds_student,subject")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "ds_student,subject"
conn.Close()
End Sub
I had the same problem as you and then i came up with this
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Folha de Obra com Tabela Clientes.accdb;Persist Security Info=True")
Dim query As String
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
conn.Open()
query = ("select * from Obras where IdCliente = " & ComboBox1.ValueMember)
cmd = New OleDb.OleDbCommand(query, conn)
da.SelectCommand = cmd
da.Fill(ds, "NomeObra")
ComboBox2.DataSource = ds.Tables(0)
ComboBox2.DisplayMember = "NomeObra"
ComboBox2.ValueMember = "IdCliente"
conn.Close()
End Sub
I hope it helps you
Related
This is my code in login button.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim InsertRecordID As Integer
Using connection As New MySqlConnection(OPConStr1),
cmd As New MySqlCommand("SELECT `StudentId` FROM `usersaccount` WHERE `StudentID` = #username AND `AccountPassword` = #password", connection)
cmd.Parameters.Add("#username", MySqlDbType.VarChar).Value = Username.Text
cmd.Parameters.Add("#password", MySqlDbType.VarChar).Value = Pass.Text
connection.Open()
InsertRecordID = CInt(cmd.ExecuteScalar())
End Using
If InsertRecordID = 0 Then
MessageBox.Show("Invalid Username Or Password")
Else
Dim OPConStr1 As String = "server=localhost;username=root;password=;database=logs"
Dim strSql = "Insert into logs.logrecord (StudentID, Status, TimeUsed, remainingTime) Values (#ID, #Status, #TimeUsed, #remainingTime);"
Using connection As New MySqlConnection(OPConStr1)
Dim cmd1 As New MySqlCommand("SELECT remainingTime FROM usersaccount.usersaccount where StudentID = " + Username.Text, connection)
Dim dt As New DataTable()
Dim adapter As New MySqlDataAdapter(cmd1)
adapter.Fill(dt)
Dim remTime1 = Convert.ToString(dt.Rows(0).ItemArray(0).ToString())
Using con As New MySqlConnection("Data Source=localhost;Initial Catalog=logs;User ID= root; password=07292021;Pooling=False"),
cmd As New MySqlCommand(strSql, con)
cmd.Parameters.Add("#ID", MySqlDbType.VarChar).Value = InsertRecordID
cmd.Parameters.Add("#Status", MySqlDbType.VarChar).Value = "LoggedIN"
cmd.Parameters.Add("#TimeUsed", MySqlDbType.VarChar).Value = "-"
cmd.Parameters.Add("#remainingTime", MySqlDbType.VarChar).Value = remTime1
con.Open()
cmd.ExecuteScalar()
Me.Close()
RemaingTime.Show()
End Using
End Using
End If
End Sub
the next one is my code for logout button
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim remsec = remseconds - OccupiedSeconds
Dim strSql = "Insert into logs.logrecord (StudentID, Date, Status,RemainingTime, TimeUsed) Values (#ID, #Log, #Status, #remainingTime, TimeUsed);"
Using cn As New MySqlConnection(OPConStr),
cmd As New MySqlCommand(strSql, cn)
cmd.Parameters.Add("#ID", MySqlDbType.VarChar).Value = SomeModule.LogInRecordID
cmd.Parameters.Add("#Log", MySqlDbType.DateTime).Value = Now()
cmd.Parameters.Add("#Status", MySqlDbType.VarChar).Value = "LoggedOUT"
cmd.Parameters.Add("#TimeUsed", MySqlDbType.Int32).Value = ""
cmd.Parameters.Add("#remainingTime", MySqlDbType.Int32).Value = remsec
cn.Open()
cmd.ExecuteScalar()
End Using
Application.Exit()
End Sub
I really don't have enough knowledge about vb and I'm still learning so bear with me. My problem is I didn't know exactly what code will be used to get the difference between loggedin and loggedout date knowing that these two datas are in same column
I'm making a tool to help a company with there staff holiday (staff holiday calculator)
I connected myself by vb and its connection to the database but I can't get any result
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New api()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'", conn.getConnection())
command.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Try
conn.getConnection.Open()
adapter.SelectCommand = command
adapter.Fill(table)
Dim sqlReader As MySqlDataReader = command.ExecuteReader()
While sqlReader.Read()
namee = sqlReader("Full_Name").ToString()
job = sqlReader("Job").ToString()
days = sqlReader("Free_Days").ToString()
MsgBox(sqlReader("Full_Name").ToString())
End While
Label2.Text = "Name : " + namee
Label3.Text = "Job : " + job
Label8.Text = "Holiday Free Days : " & days
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End Try
End Sub
I didn't get any MsgBox and there is no error and the label text didn't change
I don't have MySQL, but based on MSSQL try something like this:
Dim namee, job, days As String
Dim commandText As String = "SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'"
Dim conn As New api()
Using adapter As New MySqlDataAdapter(commandText, conn.getConnection())
adapter.SelectCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("No rows found", "ERROR")
Else
With table(0)
namee = .Item("Full_Name")
job = .Item("Job")
days = .Item("Free_Days")
End With
End If
End Using
Private Sub delivery_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sel.Items.Add("allitems")
MsgBox("alert")
Me.EntryTableAdapter.Fill(Me.TailerDataSet.entry)
viewdata.Visible = False
ConnectionState = "Data Source=SWTEAM-II-5\SQLEXPRESS;Initial Catalog=tailer;User ID=sa;Password=123"
con = New SqlConnection(ConnectionState)
con.Open()
Dim sqlquery As String
sqlquery = "Select p_name from entry"
cmd = New SqlCommand(sqlquery, con)
Dim rd As SqlDataReader = cmd.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rd)
dt.Rows.Add("allitems")
sel.ValueMember = "p_name"
sel.DisplayMember = "p_name"
sel.DataSource = dt
only combobox showing db values not manual values
Dim sqlquery As String
sqlquery = "Select p_name from entry"
cmd = New SqlCommand(sqlquery, con)
Dim adapter As New SqlDataAdapter(cmd)
sel.Items.Add("allitems")
Dim dap As New SqlDataAdapter("SELECT * FROM entry", con)
Dim ds As New DataSet
dap.Fill(ds)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
sel.Items.Add(ds.Tables(0).Rows(i).Item("p_name"))
Next
Hello Everyone Good Afternoon,
I have an Object in a form and they are Datagridview1 and a Save Button the Datagridview1 will populate data from my Database on Form_Load and the Data will show with a Corresponding Checkbox. Like the Image below
and If you here is the code for that
Private Sub loadtech()
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
Dim sql1 As MySqlCommand = New MySqlCommand("select TechName from technicians order by Category ASC", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Technician / Electrician"
End With
DataGridView1.Columns.Item(0).Width = 150
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Me.DataGridView1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
and my Question is how can I save the Checked Row in Database? Lets say I checked all of it so the Rows will be saved in Database. (Regardless of How many I Checked)
Here is my code but its not working. :(
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
conn.Open()
Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count
name = Me.DataGridView1.Rows(0).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
Next
conn.Close()
End Sub
TYSM For future help
Yes, your loop is slightly incorrect. Try using this loop and see if that fixes your issue. The issue, you didn't use the i variable. It should be placed in Row(i) and you were looping from 0 to Count when it should be 0 to Count - 1
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 Step 1
If Me.DataGridView1.Rows(i).Cells(0).Value = True Then
name = Me.DataGridView1.Rows(i).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
End If
Next
i have this 3 Forms in my project, on the second Form i have this edit button where i will edit the Listview item on the third Form, but when i select an item in the Listview and press edit, an error shows. It took me hours to find what's the problem, and i ended up here. Am i missing something?
this is my first form with listview in it.
Imports MySql.Data.MySqlClient
Public Class Form5
Public cd As Integer
Dim con As MySqlConnection
Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As New MySqlConnection
con.ConnectionString = "server=localhost;user id=root;database=db;password=root"
con.Open()
LoadPeople()
End Sub
Public Sub LoadPeople()
Dim sConnection As New MySqlConnection
sConnection.ConnectionString = "server=localhost;user id=root;database=db;password=root"
sConnection.Open()
Dim sqlQuery As String = "select * from candidate where cfname<>'Select a Candidate' AND candidacy='Filed'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
LvPeople.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With LvPeople
.Items.Add(TABLE.Rows(i)("idn"))
With .Items(.Items.Count - 1).SubItems
.Add(AddFieldValue(TABLE.Rows(i), ("cpos")))
.Add(AddFieldValue(TABLE.Rows(i), ("cfname")))
.Add(AddFieldValue(TABLE.Rows(i), ("cmname")))
.Add(AddFieldValue(TABLE.Rows(i), ("clname")))
.Add(AddFieldValue(TABLE.Rows(i), ("cparty")))
End With
End With
Next
End Sub
Private Function AddFieldValue(ByVal row As DataRow, ByVal fieldName As String) As String
If Not DBNull.Value.Equals(row.Item(fieldName)) Then
Return CStr(row.Item(fieldName))
Else
Return Nothing
End If
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Form17.Show()
End Sub
End Class
my 2nd Form
Imports MySql.Data.MySqlClient
Public Class Form17
Public cd As Integer
Public sConnection As New MySqlConnection
Private Sub Form17_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "server=localhost;user id=root;database=db;password=root"
sConnection.Open()
End If
LoadPeople3()
End Sub
Public Sub LoadPeople3()
Dim sqlQuery As String = "select * from candidate where cfname<>'Select a Candidate'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
lvPeople3.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With lvPeople3
.Items.Add(TABLE.Rows(i)("idn"))
With .Items(.Items.Count - 1).SubItems
.Add(AddFieldValue(TABLE.Rows(i), ("cfname")))
.Add(AddFieldValue(TABLE.Rows(i), ("cmname")))
.Add(AddFieldValue(TABLE.Rows(i), ("clname")))
.Add(AddFieldValue(TABLE.Rows(i), ("cyr")))
End With
End With
Next
End Sub
Private Function AddFieldValue(ByVal row As DataRow, ByVal fieldName As String) As String
If Not DBNull.Value.Equals(row.Item(fieldName)) Then
Return CStr(row.Item(fieldName))
Else
Return Nothing
End If
End Function
Private Sub lvPeople3_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvPeople3.MouseClick
cd = lvPeople3.SelectedItems(0).Selected
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If cd = Nothing Then
MsgBox("Please choose a record to edit.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "SELECT * FROM candidate WHERE cid = '" & lvPeople3.SelectedItems(0).Text & "'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTabble As New DataTable
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTabble)
End With
Form23.cd = lvPeople3.SelectedItems(0).Text
Form23.cfname = sqlTabble.Rows(0)("cfname")
Form23.cfname = sqlTabble.Rows(0)("cmname")
Form23.cfname = sqlTabble.Rows(0)("clname")
Form23.ShowDialog()
cd = Nothing
End If
End Sub
End Class
and my third Form
Imports MySql.Data.MySqlClient
Public Class Form23
Friend cd As Integer
Friend cfname As String
Friend clname As String
Friend cmname As String
Public sConnection As New MySqlConnection
Private Sub Form23_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "server=localhost;user id=root;database=db;password=root"
sConnection.Open()
End If
TextBox2.Text = cfname
TextBox3.Text = clname
TextBox4.Text = cmname
End Sub
Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
conn.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = conn
conn.Open()
If TextBox1.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
Dim sqlQuery As String = "UPDATE candidate SET cpos='" & ComboBox1.Text & "', cparty='" & TextBox1.Text & "', candidacy='Filed' WHERE cid='" & cd & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Record Updated")
Dispose()
Form5.Show()
Form17.Hide()
End If
Form5.LoadPeople()
Form17.LoadPeople3()
Me.Close()
End Sub
End Class
In Button1_Click you are accessing the first DataRow of a DataTable without checking if there is one:
Form23.cfname = sqlTabble.Rows(0)("cfname")
Form23.cfname = sqlTabble.Rows(0)("cmname")
Form23.cfname = sqlTabble.Rows(0)("clname")
You can check if there is one row by using the DataTable.Rows property:
If sqlTabble.Rows.Count > 0 Then
Form23.cfname = sqlTabble.Rows(0)("cfname")
Form23.cfname = sqlTabble.Rows(0)("cmname")
Form23.cfname = sqlTabble.Rows(0)("clname")
End If
Since you are trying to get all records according to the user's selection, i guess that you're using the wrong field. You are using the display-field but you are filtering by the ID-field:
"SELECT * FROM candidate WHERE cid = '" & lvPeople3.SelectedItems(0).Text & "'"
Maybe this is what you actually want:
"SELECT * FROM candidate WHERE cfname = '" & lvPeople3.SelectedItems(0).Text & "'"
Note that you should not use string concatenation but sql-parameters to prevent sql injection.