How to generate Custom ID - vb.net

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

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.

Apply a sequence to a table in access via vb.net

Can someone complete the following code to allow a column in a temp table to be incremented by 1 each time (starting at 300 in this example). I don't want to use an auto number, I just want to apply a sequence to the column
Dim conn As OleDbConnection = New OleDbConnection(FileLocations.connectionStringNewDb)
conn.Open()
'loop through the temp table starting at the last max test_id from tests and adding 1 to it...
Dim getTmpTestsSql As String = "SELECT * FROM TESTS_TMP;"
Dim adapter_tmp As New OleDbDataAdapter(getTmpTestsSql, conn)
Dim dt_tmp As New DataTable("TESTS_TMP_")
adapter_tmp.Fill(dt_tmp)
Dim totalrows As Integer = dt_tmp.Rows.Count
MsgBox(totalrows)
Dim sequence_sql As String = "INSERT INTO TEST_TMP VALUES (#TEST_ID)"
For i = 300 To 300 + totalrows
Dim create_sequence_cmd As New OleDb.OleDbCommand(sequence_sql, conn)
create_sequence_cmd.Parameters.AddWithValue("#A_ID", i)
'move to the next row..................
Next
conn.Close()

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..