Apply a sequence to a table in access via vb.net - 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()

Related

"There is no Row at position 0"

I would like to select the slot that value 1-53, then I need to select at above row for lot id.
The string that I need is the lot id that have 1-53 slots.
But apparently it gives me that error.
Dim selectSlots As String = " select distinct time,process,oven ,line, substring (process,8,3) as process1 from table5 Where process like '%slots =%' and oven ='15' order by oven ,line"
Dim AdpterselectSlots As New SqlDataAdapter(selectSlots, con1)
Dim DtselectSlots As New DataTable()
AdpterselectSlots.Fill(DtselectSlots)
Dim sortSLots = DtselectSlots.Rows.Count
Dim count = 0
For x As Integer = 0 To sortSLots - 1
If DtselectSlots.Rows(x).Item("process1") >= 1 And DtselectSlots.Rows(x).Item("process1") <= 53 Then
Dim line = DtselectSlots.Rows(x).Item("line") - 1
Dim selectLots As String = "select distinct time,process,oven ,line, substring (process,48,23) as process1 from table5 Where process like '%''QCheck'' Button%' and oven ='15' and line = '" & line & "' "
Dim Adpterselectlots As New SqlDataAdapter(selectLots, con1)
Dim Dtselectlots As New DataTable()
Adpterselectlots.Fill(Dtselectlots)
Dim lotID = Dtselectlots.Rows(0).Item("process1")
Dim lotID1 = lotID.Trim()
Dim cmd1 As New SqlCommand("insert into chamber1([lotnumber] ,[Oven],[line]) values ( #line , #line1,#line2 )", con1)
cmd1.Parameters.Add("#line", SqlDbType.NVarChar).Value = lotID1
cmd1.Parameters.Add("#line1", SqlDbType.NVarChar).Value = "15"
cmd1.Parameters.Add("#line2", SqlDbType.NVarChar).Value = line
con1.Open()
cmd1.ExecuteNonQuery()
con1.Close()
End If
Next
You're getting the error "there is no row at position 0" because your datatable doesn't have any rows in it, so asking for DtselectSlots.Rows(0), which you do on your first iteration of the loop (where x=0), is crashing out
Add some checking to ensure there are at least sortSlots number of rows in your table. If sortSlots is 100, your loop will run from 0 to 99. You will need 100 rows in your table to avoid a crash of "there is no row at position XX"

How to check value from looping every rows with spesific coloumn on datatable?

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?

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

Random object returns the same result multiple times

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s As New Staff
Dim strConn As String
strConn = ConfigurationManager.ConnectionStrings("ConnectionString").ToString
Dim conn As New SqlConnection(strConn)
Dim strSql As String
strSql = "SELECT StaffID FROM Staff"
Dim cmd As New SqlCommand(strSql, conn)
Dim daMember As New SqlDataAdapter(cmd)
Dim ds As New DataSet
conn.Open()
daMember.Fill(ds, "Staff")
Dim i As Integer = ds.Tables("Staff").Rows.Count - 1
For Each dr As DataRow In ds.Tables("Staff").Rows
strSql = "Update CIOPassword SET CIPassword=#CI, COPassword = #CO WHERE StaffID=#id"
Dim cmd2 As New SqlCommand(strSql, conn)
Dim output1 As String = ""
Dim output2 As String = ""
Dim random As New Random()
Dim val, val2 As Integer
For j As Integer = 0 To 9
val = random.[Next](1, 36)
val2 = random.[Next](1, 36)
output1 += ChrW(IIf(val <= 26, 64 + val, (val - 27) + 48))
output2 += ChrW(IIf(val2 <= 26, 64 + val2, (val2 - 27) + 48))
Next
cmd2.Parameters.AddWithValue("#CI", output1)
cmd2.Parameters.AddWithValue("#CO", output2)
cmd2.Parameters.AddWithValue("#id", dr(0))
cmd2.ExecuteNonQuery()
Next
GridView1.DataBind()
conn.Close()
End Sub
Basically I am trying to update each record with 2 random numbers each time the button was clicked,my problem now is, the system will update the record but the data was wrong. Example, by right all data should be different (randomly string) but for some row it was updated with same data but in randomly, something row1 row2 row3 has exactly same data for column 1 and 2 then row 3 has distinct data, second time, row1 row2 same data row3 ro4 with different data. It is in random sequence. When I add a MsgBox to do testing in the For loop the data was updated correctly with all different data.
Each time you create a Random object, it creates a new random sequence using the current time as the seed. If you create a bunch of Random objects at the same time, they will all have the same seed and therefore will generate the same sequence. As such, you should only create one Random object and reuse that same one until you are done. Don't keep creating new ones in the loop because if the loop runs too fast, they will end up not being "random".
Take a look at this site.
http://www.brettb.com/RandomNumbersInDotNet.asp
Your random.[Next] might be incorrect.