"There is no Row at position 0" - vb.net

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"

Related

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?

in for loop select statement retrieve only last column value in datagridview

Dim AR As New DD With {.DAT = {DateTimePicker1.Value.ToString("dd/M/yyyy"), DateTimePicker2.Value.ToString("dd/M/yyyy")}}
Dim sResult As String = String.Join(" , ", AR.DAT)
MessageBox.Show(sResult)
For index As Integer = 0 To AR.DAT.Length - 1
TextBox1.Text = AR.DAT(index)
Dim cMD As New SqlCommand("select [" & TextBox1.Text & "] from Attendance ", con)
Dim aD As New SqlDataAdapter
Dim dtR As New DataTable
aD.SelectCommand = cMD
aD.Fill(dtR)
DataGridView2.DataSource = dtR
con.Close()
Next
This code return only last column value... how should i retrieve all value in array to datagridview
For index As Integer = 0 To AR.DAT.Length - 1
TextBox1.Text = AR.DAT(index)
This loops through them all, nut it's too fast to see. You want to see all values in testxbox:
TextBox1.Text = TextBox1.Text + AR.DAT(index)
Better way to use listbox
ListBox1.Items.Add(index)

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()

Largest value in a column of ms access and display in a text box VB.NET

How to find the largest value in a column of a access table. and displayed in a text box. I give 101 as the default value of the column and the table is empty. I try like this.. But its not working. Code is given below
Dim empid As Integer
empid=101
TXTEMPID.Text=empid
getConnect()
Dim strSQL As String = "SELECT MAX(EMP_ID) FROM EMPLOYEE "
Dim cmd As OleDb.OleDbCommand
Dim Reader As OleDb.OleDbDataReader
cmd = New OleDb.OleDbCommand(strSQL, Conn)
Try
Conn.Open()
Reader = cmd.ExecuteReader()
If Reader.Read Then
empid = CInt(Reader("EMP_ID"))
End If
MessageBox.Show(empid)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Conn.Close()
End Try
TXTEMPID.Text = empid + 1
If the table is empty then there is no "largest value" because the table contains no values at all.
Edit
Ah, okay. It sounds like you were tripping over the fact that, for an empty table, expressions like DMax("EMP_ID","YourTable") will return Null, and Null + 1 will return Null, so how do we get started? You could try something like...
Me.txtEMP_ID.Value = Nz(DMax("EMP_ID","YourTable"), 100) + 1
...in the Form Load event, although I should mention that this type of approach can cause problems is your database is (or will ever become) multi-user.
here is the query
Select Top 1 MAX(col 2), col1 from Table1 group by col1
to get the results you have to perform
Dim cnnOLEDB As New OleDbConnection
Dim cmdOLEDB As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.Environment.CurrentDirectory & "\URDataBaseName.mdb"
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
cmdOLEDB.CommandText ="Select Top 1 MAX(col 2), col1 from Table1 group by col1"
cmdOLEDB.Connection = cnnOLEDB
txtbox.text = cmdOLEDB.ExecuteScalar().ToString()
ExecuteScalar Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored
I change my code like this given below.. Its working coooool......
getConnect()
Conn.Open()
Dim str As String
Dim newNumber As Integer
str = "SELECT MAX(EMP_ID) AS MAXIMUM FROM EMPLOYEE"
Dim cmd As OleDbCommand = New OleDbCommand(str, Conn)
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
TXTEMPID.Text = dr("MAXIMUM").ToString
newNumber = CInt(Val(TXTEMPID.Text))
If newNumber = 0 Then
newNumber = 101
TXTEMPID.Text = CStr(newNumber)
Else
newNumber = newNumber + 1
TXTEMPID.Text = CStr(newNumber)
End If
End While
End If
Conn.Close()
Thank you all for replay and comment my question