I'm trying to update a database through a datagridview but the problem I'm having is that it only updates the first row in the datagridview. Any insight will be grateful, thanks.
Dim Connection As New OleDbConnection(Get_Constring)
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("ID", Type.GetType("System.Int32"))
dt.Columns.Add("Attendance", Type.GetType("System.String"))
For i = 0 To ClassRegisterdgv.Rows.Count - 1
' If ClassRegisterdgv.Rows(i).Cells(4).Value.Equals("") Then ClassRegisterdgv.Rows(i).Cells(4).Value.Equals("Present")
Dim ID As Integer = ClassRegisterdgv.Rows(i).Cells(0).Value
Dim Attendance As String = ClassRegisterdgv.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("ID") = ID
row.Item("Attendance") = Attendance
Next
If Connection.State = ConnectionState.Closed Then
Connection.Open()
End If
Dim sqlquery As String = "UPDATE PupilInfo SET " & NewColumnCreated & " = #Attendance WHERE ID = #ID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
'For i = 0 To ClassRegisterdgv.Rows.Count - 1
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Attendance", newrow.Item(1))
.Parameters.AddWithValue("#ID", newrow.Item(0))
.Connection = Connection
MessageBox.Show(newrow.Item(1) & newrow.Item(0))
.ExecuteNonQuery()
End With
Next
Connection.Close()
ClassRegisterdgv.DataSource = Nothing
dt.Clear()
Only updates the first row because the parameters collection of the command object has not been cleaned. Try to do the following:
With sqlcommand
.CommandText = sqlquery
.Parameters.Clear() '<─────── Insert this line in your code.
.Parameters.AddWithValue("#Attendance", newrow.Item(1))
.Parameters.AddWithValue("#ID", newrow.Item(0))
.Connection = Connection
MessageBox.Show(newrow.Item(1) & newrow.Item(0))
.ExecuteNonQuery()
End With
Related
I'm currently working on my project for which I used VB.NET 2019 and SQL server. I need to create a function which auto generates IDs.
I want my IDs to be like these: P001, P002, P003 etc. Can someone show me how to code it? Below is my code
Private Sub Form4_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
BindData()
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If Con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select Max(PatientID) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If Max > 0 Then
TextBox1.Text = Max + 1
Else
TextBox1.Text = "P01"
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
You can try like this. Here 1 is an auto-generated number that may be an identity key column value from a table in SQL Server.
Dim number As Integer = 1
Dim numberText As String = "P" & number.ToString().PadLeft(3, "0")
Live demo
You can add a computed column like this in your table for auto-generating the sequences. This will reduce the chances of duplicate value runtime once more than one person will do the entry simultaneously.
Alter table Patient ADD PatientCode AS ('P' + Convert(Varchar(3),CONCAT(REPLICATE('0', 3 - LEN(PatientID)), PatientID)) )
To get the column value dynamically you can try the below code to generate function.
Private Sub GenerateSequnce()
Dim constring As String = "Data Source=TestServer;Initial Catalog=TestDB;User id = TestUser;password=test#123"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("Select Top 1 ISNULL(TaxCode, 0) from Tax_Mst Order By TaxCode Desc", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
Dim maxNumberCode = dt.Rows(0)("TaxCode").ToString()
If (maxNumberCode = "0") Then
maxNumberCode = "1"
End If
Dim numberText As String = "P" & maxNumberCode.ToString().PadLeft(3, "0")
End Using
End Using
End Using
End Using
End Sub
Here the column TaxCode is int with identity constraint.
With the minor correction in your code, you can achieve this as shown below.
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select ISNULL(Max(PatientID), 0) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If (Max = "0") Then
Max = "1"
Else
Max = CInt(Max) + 1
End If
Dim numberText As String = "P" & Max.ToString().PadLeft(3, "0")
TextBox1.Text = numberText
Catch ex As Exception
MsgBox(Err.Description)
End Try
OUTPUT
My script does not insert any data in the database table and it does not throw any error either.
The server, database and table names are correct.
The workbook is selected using filedialog (hence correct filepath) and the worksheet name seems correct too.
I have data in column A. My table is made of 2 fields:
ID (Identity, autocrement)
CustomerName
The While Loop performs 2 iterations but I have 4 records on the worksheet.
Any idea why the data does not insert in the table?
'Open the dialog box to select the file to upload
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.InitialDirectory = "C:\"
fd.Filter = "Excel Files|*.xlsx"
fd.FilterIndex = 2
fd.RestoreDirectory = True
'declare variables - edit these based on your particular situation
Dim ssqltable As String = "tbl1"
Dim myexceldataquery As String = "select CustomerName from [A$]"
'create our connection strings
Dim sexcelconnectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=Excel 12.0;"
Dim ssqlconnectionstring As String = "Data Source=AA1\SQL001_DEV001;Initial Catalog=DB_Test;Integrated Security=True"
'execute a query to erase any previous data from our destination table
Dim sclearsql As String = Convert.ToString("delete from ") & ssqltable
Dim sqlconn As New SqlClient.SqlConnection(Connections.MyMainSQLServer)
Dim sqlcmd As New SqlCommand(sclearsql, sqlconn)
sqlconn.Open()
sqlcmd.ExecuteNonQuery()
sqlconn.Close()
'series of commands to bulk copy data from the excel file into our sql table
Dim oledbconn As New OleDbConnection(sexcelconnectionstring)
Dim oledbcmd As New OleDbCommand(myexceldataquery, oledbconn)
oledbconn.Open()
Dim dr As OleDbDataReader = oledbcmd.ExecuteReader()
Dim bulkcopy As New SqlBulkCopy(ssqlconnectionstring)
bulkcopy.DestinationTableName = ssqltable
While dr.Read()
bulkcopy.WriteToServer(dr)
End While
dr.Close()
oledbconn.Close()
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyExcelSpreadsheet.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
ExcelConnection.Open()
Dim expr As String = "SELECT * FROM [Sheet1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=MMSQL1;Initial Catalog=DbName; User Id=UserName; Password=password;"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLConn)
bulkCopy.DestinationTableName = "TableToWriteToInSQLSERVER"
Try
objDR = objCmdSelect.ExecuteReader
bulCopy.WriteToServer(objDR)
objDR.Close()
SQLConn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
i have two combo boxes named comboBox1 and comboBox2. the cmbbox1 is filled with item names i have added manually before. upon selecting the item in the cmbbox1, i want to fill the cmbbox2 with the corresponding supplier which drawn from the database. sometime there are more than one supplier for an item. in that case i want to fill the combobox 2 with all the suppliers to allow the user to select the supplier..
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim dr As SqlDataReader
Dim dt As New DataTable
cn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cn
cn.Open()
cmd.CommandText = "SELECT comName FROM TblSuppliers WHERE comSitem ='" & ComboBox1.Text & "'"
dr = cmd.ExecuteReader
dt.Load(dr)
ComboBox2.Text = dt
Try this way
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim dt As New DataTable
cn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cn.Open()
cmd.Connection = cn
cmd.CommandText = "SELECT comName FROM TblSuppliers WHERE comSitem ='" & ComboBox1.Text & "'"
cmd.CommandType = CommandType.Text
adapter.SelectCommand = cmd
adapter.Fill(dt)
ComboBox2.DataSource = dt
ComboBox2.ValueMember = "comName"
ComboBox2.DisplayMember = "comName"
I need help retrieving ReceiptNO column from a database table and saving it into a TextBox or Label for referencing.
CODE:
Dim da2 As New SqlDataAdapter
da2.SelectCommand = New SqlCommand("SELECT RecepitNO FROM Receipt WHERE (PaidFor=#PaidFor AND RegNO=#RegNO)")
da2.SelectCommand.Parameters.Add("#paidFor", SqlDbType.VarChar).Value = cbMonth.Text
da2.SelectCommand.Parameters.Add("#RegNO", SqlDbType.Int).Value = lblRegNO.Text
cn.Open()
da2.Update(ds.Tables("Receipt"))
'da2.SelectCommand.ExecuteNonQuery()
da2.SelectCommand.ExecuteReader()
cn.Close()
You need to use a SqlDataReader, and then start a loop to read the values returned
This example will work assuming the ReceiptNO is a text field
cn.Open()
Dim reader = da2.SelectCommand.ExecuteReader()
while reader.Read()
textBox1.Text = reader("ReceiptNO").ToString()
End While
In alternative, if you are sure that your query returns zero or just one record and you are interested only in the ReceiptNO field, then you can use ExecuteScalar
Dim cmd = New SqlCommand("SELECT RecepitNO FROM Receipt WHERE (PaidFor=#PaidFor AND RegNO=#RegNO)")
cmd.Connection = cn
cmd.Parameters.Add("#paidFor", SqlDbType.VarChar).Value = cbMonth.Text
cmd.Parameters.Add("#RegNO", SqlDbType.Int).Value = lblRegNO.Text
cn.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
textBox1.Text = result.ToString()
End If
Here the MSDN docs on ExecuteScalar
i want to increment a no. from sql it should be like this 13-001 but it makes 13-1 here's my code
Private Sub getLastID()
Dim dr As SqlDataReader
Dim Cmd As New SqlCommand
con.Open()
With Cmd
.Connection = con
.CommandText = "SELECT * FROM tbl_student ORDER BY Student_no DESC"
End With
dr = Cmd.ExecuteReader
If dr.Read Then
lblStudentNo.Text = Val(dr.Item(0)) + 1
End If
con.Close()
End Sub
what should i do? thank you
You can use PadLeft method.
Try this:
lblStudentNo.Text = Val(dr.Item(0)) & "-" & "1".PadLeft(3, "0")