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")
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
I want to capture count of record to a variable but code is not working. Please assist
Dim PrevRgAPAC As Integer
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = "Data Source=XXXXXXXXXXX; initial catalog=XXXXXXXXXXXX; Integrated Security=true"
cmd.Connection = con
con.Open()
cmd.CommandText = "select count(record) from tblKPI where user_region='APAC' AND payroll_month='February'"
rd = cmd.ExecuteReader
If rd.HasRows Then
rd.Read()
PrevRgAPAC = rd.Item("exec")
Else
MsgBox("Not Found")
End If
Thank you
Try to use SqlCommand.ExecuteScalar Method:
PrevRgAPAC = Convert.ToInt32(cmd.ExecuteScalar())
Assuming that PrevRgAPAC is the variable in which you want to store the value of count. So your code would look like this:
Dim PrevRgAPAC As Int32 = 0
Dim sql As String = "select count(record) from tblKPI where user_region='APAC' AND payroll_month='February'"
Using conn As New SqlConnection("Data Source=XXXXXXXXXXX; initial catalog=XXXXXXXXXXXX; Integrated Security=true")
Dim cmd As New SqlCommand(sql, conn)
Try
conn.Open()
PrevRgAPAC = Convert.ToInt32(cmd.ExecuteScalar())
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
I'm trying to populate a combobox with data from SQL Server. This is my code so far. There are asterisks around the errors. Also, ignore the comments.
Private Sub frmOriginal_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connetionString As String = Nothing
Dim sqlcon As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
connetionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
sql = "select * from TickerSymbol"
sqlcon = New SqlConnection(connetionString)
Try
sqlcon.Open()
command = New SqlCommand(sql, sqlcon)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
sqlcon.Close()
cboID.DataSource = ds.Tables(0)
cboID.ValueMember = "TickerSymbol"
cboID.DisplayMember = "TickerSymbol"
Catch ex As Exception
'MessageBox.Show("Can not open connection ! ")'
End Try
End Sub
Private Sub cboID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboID.SelectedIndexChanged
Dim dr As SqlDataReader
Dim command As New SqlCommand *(queryString, connection)*
Dim dataReader As SqlDataReader = command.ExecuteReader()
Dim sqlcon As SqlConnection
Dim cmd As SqlCommand
sqlcon = New SqlConnection
sqlcon.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"
Try
sqlcon.Open()
cmd = New SqlCommand
cmd.CommandText = " select * from TickerSymbol where TickerSymbol = '" & cboID.Text & "'"
cmd = New SqlCommand(cmd.CommandText, sqlcon)
dr = cmd.ExecuteReader
While dr.Read()
'TxtID.Text = dr.GetInt32(0)'
'TxtSN.Text = dr.GetString(1)'
'TxtGender.Text = dr.GetString(2)'
'TxtPhone.Text = dr.GetInt32(3)'
'TxtAdrress.Text = dr.GetString(4)'
lblCompanyName.Text = dataReader.GetString(1)
lblPurchasePrice.Text = dataReader.GetSqlMoney(2)
lblQtyPurchased.Text = dataReader.GetInt32(3)
lblPurchaseDate.Text = dataReader.GetDateTime(4)
End While
sqlcon.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
sqlcon.Dispose()
End Sub
Please use parameterized queries as this will format values properly e.g. apostrophes in text will escape properly with parameters while without you must handle them, dates will be formatted properly too. Code is much cleaner also.
Example, syntax for Framework 3.5 and higher. If a connection string is used more than once then consider placing it in a private variable or under My.Settings under project properties.
Using cn As New SqlConnection With {.ConnectionString = "Data Source = RENEE\SQLEXPRESS;Initial Catalog=Stocks;Integrated Security = True"}
Using cmd As New SqlCommand With {.Connection = cn, .CommandText = "select * from TickerSymbol where TickerSymbol = #TickerSymbol"}
cmd.Parameters.AddWithValue("#TickerSymbol", cboID.Text)
cn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
'
'
'
End While
End If
End Using
End Using
myConnection.Open()
rtb_Address.Clear()
txt_Name.Clear()
Dim str As String
str = "SELECT * FROM table1 WHERE (cus_ID = '" & txt_ID.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader()
While dr.Read()
rtb_Address.Text = dr("cus_Addr").ToString
txt_Name.Text = dr("cus_Name").ToString
End While
myConnection.Close()
Error in dr = cmd.ExecuteReader()
dr is declared as OleDbDataReader
cus_ID is probaly a numeric data type, but you try to query it with a string: (cus_ID = 'thevalue').
Just remove the enclosing ': (cus_ID = thevalue)
or better, use a parameterized query to prevent sql-injection.
I would recommend the following:
Using cmd As New OleDbCommand("SELECT * FROM table1 WHERE cus_ID = #ID", con)
cmd.Parameters.AddWithValue("#ID", txt_ID.Text)
dr = cmd.ExecuteReader()
While dr.Read()
rtb_Address.Text = dr("cus_Addr").ToString
txt_Name.Text = dr("cus_Name").ToString
End While
End Using
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