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..
Related
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 :)
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
I want to loop every rows my datatable, the value from specific coloumn is 1,2,3. But, The value has checked only number 1. How to check every value from looping?
Dim cmd2 As New SqlCommand("Select * from Compartment where OrderFK='1254'", con)
dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As New DataTable()
dt.Load(dr) 'Here from datareader
For Each row As DataRow In dt.Rows
Dim x As Integer = dt.Rows(0)("CNumber").ToString
If x = 2 Then
Loading_No.Value = 2
Else
loading_no.value = "Empty"
End If
Next
Thank you,
If you loop with a foreach with the sets of rows retrieved by your query you should use the foreach indexer (row) to read the current value of the CNumber column, but instead of adding immediately to the TextBox add the retrieved value to a StringBuilder appending the current value to the previous read ones. At the end of the loop write everything in the TextBox value property
Dim cmd2 As New SqlCommand("Select * from Compartment where OrderFK='1254'", con)
dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As New DataTable()
dt.Load(dr) 'Here from datareader
Dim sb = new StringBuilder()
For Each row As DataRow In dt.Rows
Dim value = row("CNumber").ToString()
if value = "1" OrElse value = "2" OrElse value = "3" Then
sb.Append(row("CNumber").ToString & "," )
End If
Next
If sb.Length = 0 Then
sb.Append("Empty")
Else
' remove the last comma '
sb.Length = sb.Length - 1
End If
loading_no.Value = sb.ToString()
Notice also that you can remove the if test inside the loop modifying your query to retrieve only the records that you are interested
Dim cmdText = "Select * from Compartment where OrderFK='1254' " & _
"AND CNumber IN(1,2,3)"
To find out how many rows your loop went through just put a counter into the loop. What I am wodering about is this line:
Dim x As Integer = dt.Rows(0)("CNumber").ToString
You declare x to be an integer and assign a string to it?
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.
I want to create a custom value for the ID. For example, it will start with "CR00001" and after that it will increment the numerical portion (e.g. CR00002) when I save the data for the second time.
Here is the code I am using:
Dim cr_id As String
cr_id = "CR00001"
Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(strConnectionString)
Using sqlCommand As New MySqlCommand()
sqlCommand.Connection = SQLConnection
With sqlCommand
.CommandText = "INSERT INTO cr_record(idcr_record,Emplid,isu,Nama,date1,DeptDesc,email,change1,reasonchange,problem,priority,reasondescription,systemrequest,attachment) VALUES (#cr_id,#Emplid,#isu,#Nama,#date1,#DeptDesc,#email,#change1,#reasonchange,#problem,#priority,#reasondescription,#systemrequest,#attachment)"
.CommandType = Data.CommandType.Text
.CommandTimeout = 5000
.Parameters.AddWithValue("#cr_id", cr_id)
When you want to generate a new ID, write one function for generating the ID, and copy this code there. Keep the return type as String to return newId.
Dim newId As String
Dim stringId As String
Dim intId As Integer
Dim conn As New System.Data.SqlClient.SqlConnection("Your database query string")
Dim adpt As New System.Data.SqlClient.SqlDataAdapter("Select id from tableName Where date = (SELECT max(date) from tableName)", conn) 'Where tableName is you table
Dim ds As New DataSet
adpt.Fill(ds)
If ds.Tables(0).Rows.Count = 0 Then 'This will check whether any records are there or not
newId = "CR00001" ' If records are not there then this id will be returned
Else
stringId = ds.Tables(0).Rows(0).Item(0).ToString 'This will store your id in string format
intId = stringId.Substring(2) ' This will store only integer values from that id
intId += 1 ' Increment id by 1
newId = String.Concat("CR", intId) ' Creating new Id incremented by 1
End If
Return newId