Automatically Assign Employee Number In Datagridview - vb.net

I have 1 DataGridView with 3 columns, 1 button named as AssignID, 1 Database with EmployeeList Table.
Columns of Datagridview
Column 1 = EmployeeID
Column 2 = EmployeeName
Column 3 = Department
I'm pasting the data of EmployeeName and Department from excel into DataGridView leaving column 1 as blank. My problem is how to automatically assign the EmployeeID per Employee in the DataGridView when I press the button AssignID. The last IDNumber in the database is 10000.
Appreciate your help. Im still learning vb.net. Thanks in Advance.
Im using below code:
Private Sub AssignID_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AssignID.Click
Dim Dbcon As New OleDbConnection(connStr)
Dbcon.Open()
Dim query As String
Dim dbup As New OleDbCommand
Try
query = "SELECT Max (EmployeeID) from EmployeeList"
dbup = New OleDbCommand(query, Dbcon)
Dim EmpID As Integer
EmpID = dbup.ExecuteScalar
Dim i2 As Integer
i2 = Me.NewEmployeesDataGridview.CurrentRow.Index
NewEmployeesDataGridview.Item(0, i2).Value() = EmpID
For x As Integer = 0 To NewEmployeesDataGridview.Rows.Count - 2
NewEmployeesDataGridview.Rows(x).Cells(0).Value = NewEmployeesDataGridview.Rows(0).Cells(0).Value + 1
Next
NewEmployeesDataGridview.AllowUserToAddRows = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

If the last assigned ID in the table is 10,000, then the next ID is 10,000 + 1, that is 10,001. Therefore:
EmpID = dbup.ExecuteScalar + 1
'.Note #1: The code that is commented is not necessary
'Dim i2 As Integer
'i2 = Me.NewEmployeesDataGridview.CurrentRow.Index
'
'NewEmployeesDataGridview.Item(0, i2).Value() = EmpID
'.Note #1.
'To Rows.Count - 1 throw the correct result:
NewEmployeesDataGridview.AllowUserToAddRows = False
'For each row in the datagridview, we increase by one each ID from the last ID
For x As Integer = 0 To NewEmployeesDataGridview.Rows.Count - 1
NewEmployeesDataGridview.Rows(x).Cells(0).Value = EmpID + x
Next

I've never used that method before, but I would probably use a datadapter. It's easier to think in datarows and tables.
For example:
Dim connection As SqlConnection = New sqlconnection()
connection.ConnectionString = "<whatever your connection string is>"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
(SELECT Max (EmployeeID) from EmployeeList)
Dim ds As DataSet = New DataSet()
'fill adapter
adp.Fill(ds)
Dim DT as datatable = ds.Tables(0)
So, in DT you will have a datatable, of assuming only with 1 row with the employee you requested as its contents. Then you can grab the value like so:
Dim empID as integer = DT.rows(0).item("<name of SQL column with employee ID>")
Then you loop through each row in the datagridview, and look for the right row that has the employee you want to change.
NewEmployeesDataGridview.Rows(<integer of row>).Cells(<integer of column with IDs>).Value = empID
That's just one way to do it. The you can just find the row with that employee and assign that to the proper cell in a for loop. Or use LINQ, if you're up to it, and distinct() to find it that way more quickly.

Related

Why combo box is not loaded from join sql query

Dim cmd As New SqlCommand("SELECT MainDepartmentsTable.ID, FeesTable.ID,FeesTable.Particular,FeesTable.Fee from MainDepartmentsTable inner join SubDepartmentsTable on MainDepartmentsTable.ID = SubDepartmentsTable.MainDeptID inner join FeesTable on SubDepartmentsTable.MainDeptID = FeesTable.SubDepartmentID WHERE FeesTable.ID = '" & TextDepartmentID.Text & "' ", con)
Dim DataAdopter = New SqlDataAdapter(cmd)
Dim dt As New DataTable
DataAdopter.Fill(dt)
Load_Deparments()
First you need to validate the user input.
Using blocks ensure that you connection and command are closed and disposed.
Parameters save your database from sql injection. I had to guess at the datatype.
Private ConStr As String = "Your connection string"
Private Sub OPCode()
Dim DeptID As Integer
If Not Integer.TryParse(TextDepartmentID.Text, DeptID) Then
MessageBox.Show("Please enter a valid department ID.")
Exit Sub
End If
Dim dt As New DataTable
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand("SELECT MainDepartmentsTable.ID,
FeesTable.ID,
FeesTable.Particular,
FeesTable.Fee
from MainDepartmentsTable
inner join SubDepartmentsTable on
MainDepartmentsTable.ID = SubDepartmentsTable.MainDeptID
inner join FeesTable on
SubDepartmentsTable.MainDeptID = FeesTable.SubDepartmentID
WHERE FeesTable.ID = #DepartmentID;", con)
cmd.Parameters.Add("#DepartmentID", SqlDbType.Int).Value = DeptID
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
Load_Departments(dt)
End Sub
Private Sub Load_Departments(dt As DataTable)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Particular"
ComboBox1.ValueMember = "Fee"
End Sub
Let's simplify a bit:
Dim sql = "SELECT FeesTable.ID, CoNCAT(FeesTable.Particular, '-', FeesTable.Fee) as DisplayText
FROM
SubDepartmentsTable
inner join FeesTable on SubDepartmentsTable.MainDeptID = FeesTable.SubDepartmentID
WHERE SubDepartmentsTable.MainDeptID = #id"
Dim da As New SqlDataAdapter(sql, con)
da.SelectCommand.Parameters.AddWithValue("#id", Convert.ToInt32(TextDepartmentID.Text)) 'less worried about AWV with ints but read https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
Dim dt As New DataTable
da.Fill(dt)
'this part connects the data to the combo - it's the part you didn't show in your Q and what people are telling you is missing
yourCombo.DisplayMember = "DisplayText"
yourCombo.ValueMember = "ID"
yourCombo.DataSource = dt
This isn't intended to be a paste in fix for your problem; you've left out too much info from your question to know how to answer it exactly, so you're gonna have to modify this
Things you need to change:
The columns that are selected in the SQL - load one column you will show (I demonstrated how to combine two bits of info under one name of DisplayText) and one column for the backing value (ID)
The column that is filtered on in the where clause or the name of the text box TextDepartmentID - it seems odd to me that a Fee ID should be equal to a Department ID, so I've altered the SQL to retrieve the Fee details for a MainDepartmentID because I've assumed your textbox name is correct and that you intended to show the fees for a department via the subdepartments
Read the blog linked and perhaps choose adding a parameter in a different way
Change yourCombo to the name of your combobox
Change DisplayMember and ValueMember setting to match the names of the two columns your SQL query selects
You only need two columns if youre plumbing up a combo, but if you pass the datatable off somewhere you can add more

How to get Top Selling product with quantity from access database and display on labels

I'm making a POS system. in that, I have to include the top 3 selling products with quantity on the dashboard which is I'm unable to figure out how to do it. please help me to do the coding and the data should retrieve form access database.
This is what I did to get the top 1 selling Item. I need to get top 2nd item and 3rd item also.
Any help
Image of the result expectation
con = New OleDbConnection(cs)
con.Open()
Dim ct As String = "SELECT TOP 3 ProductName, Sum(Quantity) as Quantity FROM ProductSoldDB group by ProductName order by SUM(Quantity)"
cmd = New OleDbCommand(ct, con)
rdr = cmd.ExecuteReader()
While rdr.Read
lblProduct1Name.Text = rdr("ProductName")
lblQTYProduct1.Text = rdr("Quantity")
End While
If Not rdr Is Nothing Then
rdr.Close()
End If
con.Close()
#Always_a_learner did the hard work of getting a working Select statment.
I do not like to hold a connection open while I update the user interface. So, I filled a DataTable and passed it to the Button.Click thereby separating data access code from the user interface.
Connections and commands need to be disposed in addition to closed so use Using...End Using blocks.
Private Function RetrieveData() As DataTable
Dim sql = "SELECT TOP 10 ProductName, Sum(Quantity) as Quantity FROM ProductSoldDB Group By ProductName Order By SUM(Quantity)"
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(sql, cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
I created an array of Labels so we could loop through to fill from the DataTable. i is the index of the row, incremented by one on each iteration.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = RetrieveData()
Dim LabelsToFill = {Label1, Label2, Label3, Label4, Label5, Label6, Label7, Label8, Label9, Label10}
Dim i As Integer
For Each l As Label In LabelsToFill
l.Text = $"{dt.Rows(i)("ProductName")} - {dt.Rows(i)("Quantity")}"
i += 1
Next
End Sub
To fill 2 different labels, one for the quantity and one for the name...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dt = RetrieveData()
Dim QuanityLabels = {QLabel1, QLabel2, QLabel3, QLabel4, QLabel5, QLabel6, QLabel7, QLabel8, QLabel9, QLabel10}
Dim NameLabels = {NLabel1, NLabel2, NLabel3, NLabel4, NLabel5, NLabel6, NLabel7, NLabel8, NLabel9, NLabel10}
Dim i As Integer
For i = 0 To 9
NameLabels(i).Text = dt.Rows(i)("ProductName").ToString
QuanityLabels(i).Text = dt.Rows(i)("Quantity").ToString
Next
End Sub
EDIT
Re: The $. The $ indicates the beginning of an interpolated string which allows variables to be directly embedded if surrounded by braces { }. This became available in vb.net with Visual Studio 2015. In previous versions you can use String.Format for the same result.
l.Text = String.Format("{0} - {1})", dt.Rows(i)("ProductName"), dt.Rows(i)("Quantity"))
let's say you have 3 panel to show top 3 selling products and each panel have level in such way:
Panel 1 - label product name - lblProduct1Name , label Quanity name -lblQTYProduct1
Panel 2 - label product name - lblProduct2Name , label Quanity name -lblQTYProduct2
Panel 3 - label product name - lblProduct3Name , label Quanity name -lblQTYProduct3
We would get lblProductName and lblQTYProduct in each iteration and set value for
them.
Final code below:
con = New OleDbConnection(cs)
con.Open()
Dim ct As String = "SELECT TOP 3 ProductName, Sum(Quantity) as Quantity FROM ProductSoldDB group by ProductName order by SUM(Quantity) Desc"
cmd = New OleDbCommand(ct, con)
rdr = cmd.ExecuteReader()
Dim index As Integer = 1
While rdr.Read
Dim ctrlProduct As Control = Me.Controls.Find("lblProduct" + index.ToString() + "Name", True).FirstOrDefault()
ctrlProduct.Text = rdr("ProductName")
Dim ctrlQuantity As Control = Me.Controls.Find("lblQTYProduct" + index.ToString(), True).FirstOrDefault()
ctrlQuantity.Text = rdr("Quantity").ToString()
index = index + 1
End While
If Not rdr Is Nothing Then
rdr.Close()
End If
con.Close()
Output Here- change look and feel according to your requirement :
Here is the final code that solved my Problem with #mary 's help
Private Function RetrieveData() As DataTable
Dim sql = "SELECT TOP 3 ProductName, Sum(Quantity) as Quantity FROM ProductSoldDB group by ProductName order by Sum(Quantity) DESC"
Dim dt As New DataTable
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Desktop\EME.accdb;Persist Security Info=False;"),
cmd As New OleDbCommand(sql, cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Load_TopSellingProducts()
Dim dt = RetrieveData()
Dim QuanityLabels = {lblQTYProduct1, lblQTYProduct2, lblQTYProduct3}
Dim NameLabels = {lblProductName1, lblProductName2, lblProductName3}
Dim i As Integer
For i = 0 To 2
NameLabels(i).Text = dt.Rows(i)("ProductName").ToString
QuanityLabels(i).Text = dt.Rows(i)("Quantity").ToString
Next
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Load_TopSellingProducts()
End Sub
And Finally, I got the result as I expected
Result

VB.NET SQL Display Attendance Monthly , Yearly

I want to display all the Employee's Attendance Date As a Monthly Report.
So my database will be something like this.
How can i display them like this, all the month will be calculated. Thanks
I have tried using this code and it only return 1 result, thanks
SELECT EMPLOYEEID ,COUNT( DISTINCT checkinDate) As April FROM ATTENDANCE WHERE checkinDate BETWEEN '4/1/2018' AND '4/30/2018' GROUP BY EMPLOYEEID
It is quiet simple.First store the employee ids in a list.
Dim employeeList as New List(of String)
Dim con as New SqlConnection("connection string her")
Dim cmd as New SqlCommand("Select employeeID from tableName",con)
Dim dr as new SqlDataReader = cmd.ExecuteReader
While dr.read
employeeList.Add(dr(0).ToString)
End while
'Make sure to remove duplicates from the list'
employeeList=employeeList.Distinct.ToList()
Create a class that handles the employeeId,Attendence count and month names
Public class employees
Public id as String
Public month as String
Public atCount as Integer
End class
Now you can use the ids from the list and get the the count of the attendence of each employeeId,also make sure to create a list of the class we just made.
Dim resultList as New List(of employees) 'We are creating the list to hold the records of each employee'
Private sub addData()
Dim month as Integer = 1
Dim year as Integer = 2014 'I created two variables which would later be used in the sql statements and furthermore.'
Dim cmd as New SqlCommand("Select * from tablename Where employeeId=#empid,MONTH(checkinDate) = " + month + " AND YEAR(checkinDate) =" + year + "" , con) 'Here we use the MONTH(date) and YEAR function of SQL'
cmd.Parameters.Add("#empid",sqlDbType.VarChar)
Dim dr as SqlDataReader = cmd.ExecuteReader
For Each id in employeeList 'Here we iterate through the list'
cmd.Parameters(0).Value = id
While dr.read
Dim emp as New employees
emp.id = id
emp.month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month)
emp.atCount = emp.atCount + 1 'Here we increase the count of attendence for each record that exisits'
resultList.Add(emp) 'Finally we add the data to the list'
End While
dr.Close()
If not month = 12 Then
month = month + 1 'Firstly we check if our "month" value exceeded 12,if it did, we count one more year , if not , we count one more month'
Else
year = year + 1
month = 1
End if
Next
End sub
Now you have a list..you can save it's data to the database :
Dim cmd as new SqlCommand("Insert Into tableName(empId,MonthName,Count)VALUES(#eid,#mname,#count)")
cmd.Parameters.Add("#eid",sqlDbType.Varchar)
cmd.Parameters.Add("#mname",sqlDbType.Varchar)
cmd.Parameters.Add("#count",sqlDbType.Int)
For Each employee in resultList 'We iterate through our final list now'
cmd.Parameters(0).Value = employee.id
cmd.Parameters(1).Value = employee.month
cmd.Parameters(2).Value = employee.atCount
cmd.ExecuteNonQuery
Next
'Make sure you close the connection when all is done :)'
con.Close
Or, if you simply want to display the final list in a datagridview,consider the below code snippet :
For Each employee in resultList
Dim row As DataGridViewRow = CType(dgvw1.Rows(0).Clone(), DataGridViewRow)
row.Cells(0).Value = employee.id
row.Cells(1).Value = employee.month
row.Cells(2).Value = employee.atCount
dgvw1.Rows.Add(row)
Next
Hope this helps and enriches your knowledge :)

loop through datagrid values and use the value for other datagridview vb.net

I have a datagridview and i want to get values of the model column and get the count of the model for the other datagridview but i dont know how to loop through the value of the cells from the first datagrid.
This is the screenshot
What i want is to make the count datagrid on the right side to have 2 columns also. This is my code:
Private Sub jessy()
Dim count As Integer = 0
Dim a = requestDatagridview.Rows.Count
MsgBox(a)
For Each row As DataGridViewRow In requestDatagridview.Rows
Label1.Text = row.Cells("model").Value
conn = New MySqlConnection
conn.ConnectionString = "server=127.0.0.1; port=3306; username=root; password=""; database= atos_db"
Dim dbDataset1 As New DataTable
Dim sda1 As New MySqlDataAdapter
Dim bsource1 As New BindingSource
Try
conn.Open()
Dim query As String
query = "select count(serial_no) as 'Count' from atos_db.equip_tbl left join atos_db.itemdetails_tbl on equip_tbl.itemdetails_id=itemdetails_tbl.itemdetails_id left join atos_db.brand_tbl on itemdetails_tbl.brand_id = brand_tbl.brand_id left join atos_db.item_tbl on brand_tbl.item_id=item_tbl.item_id where model='" & a & "'"
comm = New MySqlCommand(query, conn)
sda1.SelectCommand = comm
sda1.Fill(dbDataset1)
bsource1.DataSource = dbDataset1
countDatagridview.DataSource = bsource1
sda1.Update(dbDataset1)
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
Next
End Sub
The following code may help you :
' Create a variable to store your value (example qty)
Dim total As Integer = 0
' Loop through your datagridview rows.
For i As Integer = 0 To dtgv.Rows.Count - 1
' Add the qty value of the current row to total
total = total + dtgv.Rows(i).Cells(4).Value
Next
' Then, modify the value of the second dtgv
dtgv2.Rows(0).Cells(0).Value = total

VB.Net assign values to datatable

Hi I have the String and integers to which some values are assigned. now i need to read the string and integer values and assigned them to the datatable which i have created using VB.Net..
If dt.Rows.Count > 0 Then
For n As Integer = 0 To dt.Rows.Count - 1
EmployeeNo = (dt.Rows(n)(0))
EmpName = (dt.Rows(n)(1)).ToString
Commission = CDbl(dt.Rows(n)(2))
'I need to read one by one and assign the [EmployeeNo,EmpName,Commission]
'to the dataset DtEmployee in which Employee is the table and EmpNo, EmpName, Commission 'are the coloumns..
Next
End If
Please help me on this..
Try this to dump whole sheet to DataTable:
var connectionString = " Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES;IMEX=1";"
var sheetName = "Sheet1";
using (var con = new OleDbConnection(connectionString))
{
con.Open();
var table = new DataTable(sheetName);
var query = "SELECT * FROM [" + sheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(table);
return table;
}
Edit: As per updated question
If dt.Rows.Count > 0 Then
For n As Integer = 0 To dt.Rows.Count - 1
EmployeeNo = (dt.Rows(n)(0))
EmpName = (dt.Rows(n)(1)).ToString
Commission = CDbl(dt.Rows(n)(2))
'I need to read one by one and assign the [EmployeeNo,EmpName,Commission]
'to the dataset DtEmployee in which Employee is the table and EmpNo, EmpName, Commission 'are the coloumns..
Dim dataRow As DataRow = DtEmployee.Tables("Employee").AsEnumerable().Where(Function(row) row.Field(Of String)("EmpNo") = EmployeeNo).SingleOrDefault()
If dataRow IsNot Nothing Then
//Set your DataRow
dataRow("EmpName") = EmpName
dataRow("Commission ") = Commission
DtEmployee.AcceptChanges();
End If
Next
End If
Find the Row from the DtEmployee table and update that one or if you want to add new rows then do not find row, just create new row and set value and add to DtEmployee
DataRow dataRow = DtEmployee.Tables("Employee").NewRow()
//Set your DataRow
dataRow("EmpName") = EmpName
dataRow("Commission ") = Commission
DtEmployee.Tables("Employee").Rows.Add(dataRow)
Hope this help..