Auto generated alphanumeric ID in VB.Net - vb.net

Hi everyone I'm new in this site and I want a help from you guys. I'm currently working on my project which i used is VB.net 2010. I need help with my ID that will auto generate.
I want my ID to be like these:
CAT001
CAT002
CAT003
and so on.

Assuming you have some sort of counter for the id number called _idNumber, then you could have something like:
Dim idString as String = String.Format("CAT{0}", _idNumber.ToString("D3"))

Private Sub autogenerate_ID()
Dim mysqlconnection As MySqlConnection
Dim command As New MySqlCommand
MySqlConnection = New MySqlConnection()
MySqlConnection.ConnectionString = " server = localhost; user id = root; password=; database = your database "
Command.Connection = MySqlConnection
mysqlconnection.Open()
Dim sqlquery = "select Max(ID) from yourtable "
command.CommandText = sqlquery
Dim ID As Integer
Dim value As String
value = command.ExecuteScalar().ToString()
If String.IsNullOrEmpty(value) Then
value = "CAT000"
End If
value = value.Substring(3)
Int32.TryParse(value, ID)
ID = ID + 1
value = "CAT" + ID.ToString("D3")
Txt.Text = value
command.Dispose()
mysqlconnection.Close()
mysqlconnection.Dispose()
End Sub

Related

how to Generate alphanumeric id with auto changing alphabets?

i am trying to create alphanumeric id in which i am starting from aa001. when aa001 reach to aa999 then it should be ba001 and when it reach to ba999 it should be ca001 and it should go on to all alphabets so that there will never ending alphanumeric id and it should be unique. i do not want to create so long id bcoz it will be difficult to type. how can it be done?
Dim mysqlconnection As SqlConnection
Dim command As New SqlCommand
mysqlconnection = New SqlConnection()
mysqlconnection.ConnectionString = "server= .\SQLEXPRESS; database = software; integrated security=true"
command.Connection = mysqlconnection
mysqlconnection.Open()
Dim sqlquery = "select Max(stockid) from stockdata "
command.CommandText = sqlquery
Dim ID As Integer
Dim value As String
value = command.ExecuteScalar().ToString()
If String.IsNullOrEmpty(value) Then
value = "aa000"
End If
value = value.Substring(2)
Int32.TryParse(value, ID)
ID = ID + 1
value = "aa" + ID.ToString("D3")
Label12.Text = value
command.Dispose()
mysqlconnection.Close()
mysqlconnection.Dispose()
End Sub

ID numbers with text

Help. So this is my code and my database table. The itemcat is based on the tbl_category and it gives IN, PF, SS, SV + the number of the id.
As you can see the. PF003 and SS003 have the same number. How to change it to SS004 automatically?
Private Sub AutoGenerateID()
Dim mysqlconnection As MySqlConnection
Dim command As New MySqlCommand
mysqlconnection = New MySqlConnection()
mysqlconnection.ConnectionString = "Server=localhost;User=root;Password=;Database=debis"
command.Connection = mysqlconnection
mysqlconnection.Open()
da = New MySqlDataAdapter("select * from tbl_category where catname = '" & cmbcat.SelectedItem & "'", con)
ds.Reset()
da.Fill(ds)
Dim sqlquery = "select Max(itemid) from tbl_item "
command.CommandText = sqlquery
Dim ID As Integer
Dim value As String
Dim i As Integer
For i = 0 To ds.Tables(0).Rows.Count - 1
value = command.ExecuteScalar().ToString()
If String.IsNullOrEmpty(value) Then
value = (ds.Tables(0).Rows(i).Item("catid")) + "0000"
End If
value = value.Substring(3)
Int32.TryParse(value, ID)
ID = ID + 1
value = (ds.Tables(0).Rows(i).Item("catid")) + ID.ToString("D3")
tbitemid.Text = value
Next
command.Dispose()
mysqlconnection.Close()
mysqlconnection.Dispose()
End Sub
This is the image of the table
If the first part is always 2 characters long then you can split your string to increment only the number part.
intValue = val(strings.mid(value,3))
intValue = intValue + 1
Also, you should hide/change your server address, user/password when you post your code on the web.

Add Column to DataTable before exporting to Excel file

I have a DataTable that is built like this:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Then it is converted to a DataView and exported to Excel like this:
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I want to add another column and fill it with data before I export to Excel. Here's what I'm doing now to add the column:
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
Then to populate it:
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
Dim reader As SqlDataReader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next row
But I get a "System.FormatException: Input string was not in a correct format." error when I run the app. It doesn't seem to like these lines:
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
I think I have more than one issue here because even if I comment out the loop that fills the data in, the column I created doesn't show up in the Excel file. Any help would be much appreciated. Thanks!
EDIT:
Okay, I was grabbing the column name instead of the actual data in the column... because I'm an idiot. The new column still doesn't show up in the exported Excel file. Here's the updated code:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
'set the values of the new column based on info pulled from db
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Dim reader As SqlDataReader
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row.Item(0))
Dim pID As String = row.Item(2).ToString
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
reader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
myConn.Close()
Next row
dt.AcceptChanges()
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I suppose that you want to search your MyTable if it contains a record with the uid and the pid for every row present in your dt table.
If this is your intent then your could write something like this
Dim qry As String = "SELECT UserID FROM [MyTable] WHERE [UserID] = #uid AND [PassID] = #pid"
Using myConn = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Using myCommand = new SqlCommand(qry, myConn)
myConn.Open()
myCommand.Parameters.Add("#uid", OleDbType.Integer)
myCommand.Parameters.Add("#pid", OleDbType.VarWChar)
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row(0))
Dim pID As String = row(1).ToString()
cmd.Parameters("#uid").Value = uID
cmd.Parameters("#pid").Value = pID
Dim result = myCommand.ExecuteScalar()
If result IsNot Nothing Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next
End Using
End Using
Of course the exporting to Excel of the DataTable changed with the new column should be done AFTER the add of the column and this code that updates it
In this code the opening of the connection and the creation of the command is done before entering the loop over your rows. The parameterized query holds the new values extracted from your ROWS not from your column names and instead of a more expensive ExecuteReader, just use an ExecuteScalar. If the record is found the ExecuteScalar just returns the UserID instead of a full reader.
The issue was in my CreateExcelFile() method. I inherited the app I'm modifying and assumed the method dynamically read the data in the DataTable and built the spreadsheet. In reality, it was searching the DataTable for specific values and ignored everything else.
2 lines of code later, I'm done.

How to generate Custom ID

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

need to get value from sql query

Through ADO,I like to do the following query:
select name, address, zip from terr where id = '33334'
I like then to assign name, addess, zip to variables so that I can assign it later in my program.
How do I do this with VB.NET ADO?
Try somethign like this:
Dim dbName As String
Dim dbAddress As String
Dim dbZip As String
Using connObj As New SqlClient.SqlConnection("<connectionString>")
Using cmdObj As New SqlClient.SqlCommand("select name, address, zip from terr where id = '33334'", connObj)
connObj.Open()
Using readerObj As SqlClient.SqlDataReader = cmdObj.ExecuteReader
'This will loop through all returned records
While readerObj.Read
dbName = readerObj("name").ToString
dbAddress = readerObj("address").ToString
dbZip = readerObj("zip").ToString
'handle returned value before next loop here
End While
End Using
connObj.Close()
End Using
End Using
Also, you should look into parameterizing the value for the where clause.
You need a DataBase (i assume MS Sql-Server), a Connection and a DataAdapter to fill a DataTable. Then you have all you need. Here's an example:
Public Function GetUser(UserId As Int32) As DataRow
Using con = New SqlConnection(My.Settings.RM2ConnectionString)
Using cmd = New SqlCommand("select name, address, zip from terr where id = #id", con)
cmd.Parameters.AddWithValue("#id", UserId)
Dim da = New SqlDataAdapter(cmd)
Dim tblUser = New DataTable
da.Fill(tblUser)
If tblUser.Rows.Count <> 0 Then
Return tblUser(0)
Else
Return Nothing
End If
End Using
End Using
End Function
execute a SqlCommand from SQLDatareader, like:
Dim vVendedor As New SqlCommand("SELECT user FROM users", mConeccion)
vDatosVen = vVendedor.ExecuteReader
vVendedor = Nothing
and to get te value:
While vDatosVen.Read()
vUser = vDatosVen("user")
End While
Here's what i did...
Private Sub btn_Connect_Click(sender As Object, e As EventArgs) Handles btn_Connect.Click
Dim sql_connection As New MySqlConnection
Dim sql_query As New MySqlCommand
Dim sql_result As MySqlDataReader
sql_connection.ConnectionString = "Server=localhost;Database=hidden;Uid=root;Pwd=;"
sql_query.Connection = sql_connection
sql_connection.Open()
sql_query.CommandText = "SELECT Entry,name FROM table WHERE entry=1;"
sql_result = sql_query.ExecuteReader
If sql_result.HasRows Then
Do While sql_result.Read()
Dim query_result As String
query_result = sql_result("name")
MsgBox(query_result)
Loop
Else
MsgBox("No results found.")
End If