sort two dimensional array by descending vb.net - vb.net

Please could you help me sort this by 2nd column descending?
Dim ds As New DataSet()
conn.Open()
techSpeciality = LB_techFaultType.Text
techZone = LB_TechZone.Text
Dim strSQL As String = "SELECT Tech_ID, Last_Zone FROM Technician_List WHERE Availability=TRUE AND Speciality='" & techSpeciality & "' AND Last_Zone='" & techZone & "'"
Dim da As New OleDbDataAdapter(strSQL, conn)
da.Fill(ds)
'2D array
Dim values(ds.Tables(0).Rows.Count - 1, 2) As Integer
'for loop between 0 and all available technicians
For value As Integer = 0 To ds.Tables(0).Rows.Count - 1
'Tech_ID column
values(value, 0) = ds.Tables(0).Rows(value).Item(0).value()
'Zone column, converts negative value to a positive and minus' the selected techZone
Math.Abs(values(value, 1) = techZone - ds.Tables(0).Rows(value).Item(1).value())
Next

Modify this line:
Dim strSQL As String = "SELECT Tech_ID, Last_Zone" & _
" FROM Technician_List WHERE" & _
" Availability=TRUE AND Speciality='" & techSpeciality & _
"' AND Last_Zone='" & techZone & _
"' ORDER BY Last_Zone DESC"
For more information on the ORDER BY keywords:
http://www.w3schools.com/sql/sql_orderby.asp

Another option is to do ORDER BY 2 DESC, instead of directly specifying the column name.

Related

SSIS Create and Attaching file to the email

I've 2 sqlreaders and both should loop through it and second sqlreader data should create a table and inserting into the excel sheet.
Lets say
I've sqlreader and sqlreader1
sqlreader has some data which is required to get sqlreader1
I'm able to get sqlreader1 data as I expected
but once I loaded data to datatable, I'm loosing sqlreader1 and not able to see any info in sqlreader1
If SqlDataReader.HasRows Then
Do While SqlDataReader.Read()
Dim ExcelFileName As String = Dts.Variables("User::FolderPath").Value.ToString() + "Accrual_Input_Summary_Q" + SqlDataReader.Item("Accrual_Quarter").ToString() + " FY-" + SqlDataReader.Item("Accrual_FY").ToString() + ".xlsx"
'Dim recipientName As String = SqlDataReader.Item("recipient_name").ToString()
'Dim recipientEmail As String = SqlDataReader.Item("Recipient_Email").ToString()
Try
If System.IO.File.Exists(ExcelFileName) = True Then
System.IO.File.Delete(ExcelFileName)
End If
Dim SqlCmd1 As New SqlCommand("[POT].[PROC_POT_Accrual_Reminder_Summary]", SqlCon)
SqlCmd1.CommandType = CommandType.StoredProcedure
SqlCmd1.CommandTimeout = 0
SqlCmd1.Parameters.AddWithValue("#Qtype", "Accrual_Summary")
SqlCmd1.Parameters.AddWithValue("#Accrual_Created_By_Email", SqlDataReader.Item("Recipient_Email").ToString())
Dim SqlDataReader1 As SqlDataReader = SqlCmd1.ExecuteReader()
' connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" &
'"Data Source=" & ExcelFileName &
'";Extended Properties=Excel 12.0 Xml;HDR=YES;"
If SqlDataReader1.HasRows Then
While SqlDataReader1.Read()
Dim connectionString As String
Dim excelConnection As OleDbConnection
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & ExcelFileName & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES;"""
excelConnection = New OleDbConnection(connectionString)
Dim Excel_OLE_Cmd As OleDbCommand = New OleDbCommand()
Dim recipientName As String = SqlDataReader1.Item("Created_By_Name").ToString()
Dim recipientEmail As String = SqlDataReader1.Item("CostCenterAnalyst").ToString()
Dim costCenterOwner As String = SqlDataReader1.Item("CostCenterOwner").ToString()
Dim TableColumns As String = ""
Dim dtCustomers As New DataTable("sqlDataTable")
**dtCustomers.Load(SqlDataReader1)**
For Each column As DataColumn In dtCustomers.Columns
TableColumns += column.ToString() & "],["
Next
TableColumns = ("[" & TableColumns.Replace(",", " Text,").TrimEnd(","c))
TableColumns = TableColumns.Remove(TableColumns.Length - 2)
excelConnection.ConnectionString = connectionString
excelConnection.Open()
Excel_OLE_Cmd.Connection = excelConnection
Excel_OLE_Cmd.CommandText = "Create table " & "Sheet1" & " (" & TableColumns & ")"
Excel_OLE_Cmd.ExecuteNonQuery()
Dim sqlCommandInsert As String = ""
Dim sqlCommandValue As String = ""
For Each dataColumn As DataColumn In dtCustomers.Columns
sqlCommandValue += dataColumn.ToString() & "],["
Next
sqlCommandValue = "[" & sqlCommandValue.TrimEnd(","c)
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2)
sqlCommandInsert = "INSERT into " & "Sheet1" & "(" & sqlCommandValue & ") VALUES("
Dim columnCount As Integer = dtCustomers.Columns.Count
For Each row As DataRow In dtCustomers.Rows
Dim columnvalues As String = ""
For i As Integer = 0 To columnCount - 1
Dim index As Integer = dtCustomers.Rows.IndexOf(row)
columnvalues += "'" & dtCustomers.Rows(index).ItemArray(i).ToString() & "',"
Next
columnvalues = columnvalues.TrimEnd(","c)
Dim command As String = sqlCommandInsert & columnvalues & ")"
Excel_OLE_Cmd.CommandText = command
Excel_OLE_Cmd.ExecuteNonQuery()
Next
excelConnection.Close()
StrMailBody_Inner = " Hello Cost Center Analyst (" & recipientName & "), <br/><br/> PFA accrual inputs for the current quarter. Please review & take appropriate action click <a href='http://podashboarddev/' target='_blank'>here</a>.<br/><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <u>Note</u><br/>"
StrMailBody_Inner = StrMailBody_Inner + " <ol>"
StrMailBody_Inner = StrMailBody_Inner + " <li>The accrual inputs provided doesn't interface with SAP. You will still need to post the necessary accrual JV.</li>"
StrMailBody_Inner = StrMailBody_Inner + " <li>CCA can leverage the tool for accrual tracking.</li>"
StrMailBody_Inner = StrMailBody_Inner + " </ol>"
Using myMessage As New MailMessage(Dts.Variables("email_from").Value, recipientEmail)
Dim copy As MailAddress = New MailAddress(costCenterOwner)
myMessage.CC.Add(copy)
myMessage.IsBodyHtml = True
myMessage.Subject = Dts.Variables("email_subject").Value
myMessage.Body = StrMailBody.ToString().Replace("$$$$Mail_Body$$$$", StrMailBody_Inner)
myMessage.Priority = System.Net.Mail.MailPriority.High
myMessage.Attachments.Add(New Attachment(ExcelFileName))
mySmtpClient = New SmtpClient("mailserver.amat.com")
mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
'mySmtpClient.Send(myMessage)
Dim str_SQL As String
str_SQL = "INSERT INTO [POT].[tbl_POT_Open_PO_Accrual_Reminder_History] ([Recipient_Email], [Reminder_Type]) VALUES ('" + SqlDataReader.Item("recipient_email").ToString() + "', 'Accrual_Summary');"
Dim SqlCmdHist As New SqlCommand(str_SQL, SqlCon)
SqlCmdHist.CommandType = CommandType.Text
SqlCmdHist.CommandTimeout = 0
SqlCmdHist.ExecuteNonQuery()
SqlCmdHist.Dispose()
End Using
End While
SqlDataReader1.Close()
End If
Once I load data to Datatable using this
dtCustomers.Load(SqlDataReader1)
before load data:
after load data:
I'm missing the sqlreader1 and i'm unable to loop through it.
it is giving Invalid attempt to call Read when reader is closed.
Note: I've enabled MultipleActiveResultSets
can we do any other things that we can do to resolve this issue

How to merge from multiple field of access database to one column fo datagridview in vb.net using dataset

How to convert recordset to dataset because while 200 more data load to datagridview that after datagrid has been very slow, so i want my code change to load datagrid by dataset but i dont know dataset code how to merge multiple field of database data into one column in datagrid, So please help me...
Private Sub FLEX1_LOAD()
DataGridView1.Rows.Clear()
Dim strsql As String
Dim rs2 As ADODB.Recordset
strsql = "select * from voterlist where AREAID='" & Trim(lblAreaid.Text) & "'"
rs2 = New ADODB.Recordset
Call dbconnect2()
rs2.Open(strsql,conne2,ADODB.CursorTypeEnum.adOpenStatic,ADODB.LockTypeEnum.adLockPessimistic)
If rs2.RecordCount > 0 Then
rs2.MoveFirst()
For I = 0 To rs2.RecordCount - 1
DataGridView1.Rows.Add(1)
DataGridView1.Rows(J).Cells(0).Value = J + 1
DataGridView1.Rows(J).Cells(1).Value =rs2.Fields("ID").Value
DataGridView1.Rows(J).Cells(2).Value = rs2.Fields("NAM").Value & " " & rs2.Fields("SURNAME").Value & "/" & rs2.Fields("RTYPE").Value & "-" & rs2.Fields("RNAME").Value & " " & rs2.Fields("RSURNAME").Value
DataGridView1.Rows(J).Cells(3).Value = rs2.Fields("AGE").Value
J = J + 1
rs2.MoveNext()
Next
End If
rs2.Close()
rs2 = Nothing
conne2.Close()
End Sub

insert and update in vb.net with access index out of range

i have application i want it to do
1- insert the first statement .
2-get the (maxid) of the invoice
3-insert the detail of the invoice with the Id .
it give me this error
index out of range .
Private Sub insert()
Dim invoiceday As Date = Today
Dim userid As Integer
Dim clientid As Integer
Dim note As String
If clients.Visible = True Then
userid = 1
clientid = 2
note = "cash"
Else
userid = 2
clientid = 6
note = "credit"
End If
Dim query1 As String = " insert into invoices([purchasedate],clientid,[Note],userID,total,disq) Values ( '" & CDate(invoiceday) & "','" & clientid & "','" & note & "','" & userid & "','" & totalprice.Text & "','" & txtdis.Text & "')"
samselect2(query1)
Dim maxinvoice As Integer
maxinvoice = invoiceid()
For Each row As DataGridViewRow In dvsale.Rows
Dim query As String = " insert into invoicede(invoiceid,barcode,doaname,Qty,Price,qtyprice) Values ('" & maxinvoice + 1 & "','" & row.Cells("barcode").Value & "','" & row.Cells("doaname").Value & "','" & row.Cells("qty").Value & "','" & row.Cells("price").Value & "','" & row.Cells("tqty").Value & "')"
samselect2(query)
Next
End Sub
this the class of the samselect2
Public Sub samselect2(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
End Try
con.Close()
da.Dispose()
End Sub
and the invoiceid max number
Private Function invoiceid()
checkConnection()
Dim strQ As String = "SELECT max(invoiceID)as MaxIDbatch from invoices "
Dim cmdQ As OleDbCommand = New OleDbCommand(strQ, con)
Dim result = cmdQ.ExecuteScalar()
If result IsNot Nothing Then
Dim x As Integer = 0
Return x
Else
Return result
End If
End Function
Although I don't fully understand your question, I notice a couple things: 1) It appears that InvoiceID is not an auto-incrementing identity field, and it probably should be. (Check out "Is Identity".) If it were, you could insert and specify all fields except that one, and the number would increment automatically. 2) In your for...each, you are not increasing maxinvoice at all with each iteration through the loop. Although you're using maxinvoice+1, it will still be the same number each time.
Still, all of that should be unnecessary if you make InvoiceID an identity field.

VB.net Retrieving dataset values from a particular column into a string

I need to copy structure of selected database to a new database. How is it possible? I am not able to retrieve the DataSet value. I need to use this value to retrieve the table names associated with the database. Here is my code.
cmd.CommandText = "create database " & txtCustId.Text & "AAA"
cmd.ExecuteNonQuery()
Dim dtadapt As New SqlDataAdapter("select table_name from " & name & ".INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'", comm_con)
Dim dtset As New DataSet
dtadapt.Fill(dtset)
Dim dttb As DataTable = dtset.Tables(0)
'Dim row As Integer = 1
Dim arrS As String = ""
while dttb.Rows.Count > 0
'arrS =Convert.ToString(dtset.Tables[i].Rows[0]["table_name"])
arrS = dttb("table_name").ToString
cmd.CommandText = " SELECT * INTO " & txtCustId.Text & "AAA.dbo." & arrS & " FROM " & name & ".dbo." & arrS & " where 1=1"
cmd.ExecuteNonQuery()
'MessageBox.Show("done")
End while

Function to return info

I changed the above to use string builder but some reason its not comming through on the loop its returning ok through the OrdersLine variable but not to the stream . Below is the loop im declaring it in
Dim OrdersLine As String
For Each item As String In split
For Each thisEntry As DataRow In orderHeaderInformation.Rows
orderLineInformation = connection.SqlSelectToDataTable(scriptBuilder.GetOrderLineInformation(item, thisEntry.Item("location")))
Dim orderNumber = From row In newEntries.AsEnumerable()
Select row.Field(Of String)("ordernumber") Distinct
For Each c In IO.Path.GetInvalidFileNameChars
filename = thisEntry.Item("orderNumber").ToString().Replace(c, "")
Next
ediExportPath = configuration.EditExport
filename = ediExportPath & "\" & filename & "_" & thisEntry.Item("location") & ".edi"
Dim streamWriter As New IO.StreamWriter(filename)
OrdersLine = ExportOrdersLine(orderLineInformation).ToString()
streamWriter.WriteLine(OrdersLine)
streamWriter.Close()
streamWriter.Dispose()
Next
Next
Public Function ExportOrdersLine(editProductLine As DataTable) As String
Dim retVal As String
Dim newRecord As infoEDILine
Dim filenameWithoutExtensions As String
Dim i As Integer = 1
Dim edilIneOrder As New StringBuilder
For Each thisentry In editProductLine.Rows
edilIneOrder.AppendLine("LIN+" & i & thisentry.Item("TagBcode") & ":EN'")
edilIneOrder.AppendLine("PIA+1" & thisentry.Item("PLU") & ":SA'")
edilIneOrder.AppendLine("IMD+C++CU'")
edilIneOrder.AppendLine("IMD+F++:::" & thisentry.Item("Style.Description") & "'")
edilIneOrder.AppendLine("QTY+" & thisentry.Item("PLU") & ":1'")
edilIneOrder.AppendLine("QTY+" & thisentry.Item("OnOrder") & ":1'")
edilIneOrder.AppendLine("TAX+7+VAT+++:::00" & thisentry.item("VatRate") & "'")
' if the vat rate is zero add three zeros to above line
' if the vat rate is not zero add only two 00 lke above line
' if no decimal places add one decimal place of zero
edilIneOrder.AppendLine("MOA+203:" & thisentry.item("LineNetCost") & "'")
edilIneOrder.AppendLine("PRI++AAA:" & thisentry.Item("GrossCost") & "'")
edilIneOrder.AppendLine("PRI++AAB:" & thisentry.Item("WholeSaleCost") & "'")
edilIneOrder.AppendLine("UNS+S'")
i = i + 1
Next
Return edilIneOrder.ToString()
End Function
Turns Out I was missing
streamWriter.AutoFlush = True