Update previous row - sql

I have an Excel file that contains some datas that I want to export into an Access db. In the C column I've got a field called 'Description'. Usually this field occupy just one cell, but it can happens that is more long.
In this case, for example, AP.01 has got 5 rows of description. How can update the first row with the next rows?
Public Sub updateDB(ByVal PathDB As String, str As String, id As Integer)
Dim db As New cDB
Dim v As New cVoce
Dim rs As ADODB.Recordset = db.RecordSet
v.Description = str
db.connetti_DB(PathDB)
db.get_rs("UPDATE Voice SET Description = '" + v.Description + "' WHERE id= '"+id+"'")
End Sub
Public Function get_rs(ByVal query As String) As ADODB.Recordset
If db Is Nothing Then rs = Nothing : Return rs
rs = New ADODB.Recordset
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
rs.LockType = ADODB.LockTypeEnum.adLockOptimistic
rs.Open(query, db)
Return rs
End Function
This code doesn't work because I update my current row, for this reason is useless the UPDATE instruction. How can I fix my code?
EDIT I post here the For loop
For r = 2 To grid.RowCount - 1
vett = Split(grid(r, 1).Text)
total = UBound(Split(grid(r, 1).Text, "."))
If grid(r, 1).Text <> "" Then
Select Case total
Case 0
Dim chapter As New cChapter
flag = 1
id = id + 1
chapter.Cod = grid(r, 1).Text.Substring(0, 1)
chapter.Description = grid(r, 3).Text
If Left(vett(0), 1) >= Chr(65) And Left(vett(0), 1) <= Chr(90) Then
chapter.Cod = Left(vett(0), 1)
oldChap = chap.Cod
If chapter.Cod <> oldCap Then
chapters.Add(chapter)
End If
End If
chapters.Add(chapter)
stringChap = chap.Description
Dim par As New cParagraph
If Left(vett(0), 2) >= Chr(65) And Left(vett(0), 2) <= Chr(90) Then
par.Cod = Left(vett(0), 2)
par.Cod_Chapter = Left(vett(0), 1)
oldPar = par.Cod
If par.Cod <> oldPar Then
paragraphs.Add(par)
End If
End If
If grid(r, 3).Text.Length > 255 Then
par.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
Else
par.Description = grid(r, 3).Text.ToString
End If
paragraphs.Add(par)
stringPar = par.Description
Case 1
flag = 2
id = id + 1
c_Voc = voc.Cod_Chapter
p_Voc = voc.Cod_Paragraph
voc.Cod_Chapter = grid(r, 1).Text.Substring(0, 1)
voc.Cod_Paragraph = grid(r, 1).Text.Split(".")(0)
voc.Cod_Voice = Right(vett(0), 2)
If grid(r, 3).Text.Length > 255 Then
voc.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
Else
voc.Description = grid(r, 3).Text.ToString
If voc.Description.EndsWith("-") Then
a = Replace(voc.Description, "-", "")
voc.Description = a
End If
End If
stringVoice = voc.Description
voices.Add(voc)
voices.Save_DB(dbDest)
Case 2
flag = 3
id = id + 1
sVoice = New cVoice
oldSvoice = voice.Cod_SVoice
sVoice.Cod_SVoice = Left(vett(0), 2)
If sVoice.Cod_SVoce <> oldSvoice Then
voices.Add(sVoice)
voices.Save_DB(dbDest)
End If
If grid(r, 3).Text.Length > 255 Then
sVoice.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
Else
sVoice.Description = grid(r, 3).Text
End If
stringSvoice = sVoice.Description
sVoice.Cod_Voce = Left(vett(0), 5)
sVoice.Price1 = grid(r, 12).Text
sVoice.Price2 = sVoice.Price1
sVoice.UniMi = grid(r, 11).Text
sVoce.Sep = "."
voices.Add(sVoce)
voices.Save_DB(dbDest)
End Select
Else
If flag = 1 Then
stringChap = grid(r, 3).Text
chap.Description = stringChap & grid(r, 3).Text
stringPar = grid(r, 3).Text
paragraph.Description = stringPar & grid(r, 3).Text
End If
If flag = 2 Then
stringVoice = grid(r, 3).Text
voc.Description = voc.Description & stringVoice
voices.updateDB(dbDest, stringVoice, id)
voices.Add(voc)
End If
If flag = 3 Then
stringSvoice = grid(r, 3).Text
sVoice.Description = stringSvoice & grid(r, 3).Text
voices.Add(sVoice)
End If
chapter.Save_DB(dbDest)
paragraph.Save_DB(dbDest)
voice.Save_DB(dbDest)
End If
Next
EDIT2 I declared id As Integer and when Code column has a value then id=id+1. In this way I always know which row I have to modify. I modified also updateDB (now I'm using 3 parameters) and I added a WHERE condition into my query. Despite the update, nothing has changed

In database you cannot store records without PrimaryKey (actually you can, but it is bad idea). Since in your solution id is in fact Excel row number (sorry if I'm not correct but it looks like from code) it could be very hard to maintain it in future (in case someone add or remove description row). It would be better to change id column to text and use code as PK.
Storing description then could be solved in 2 ways:
1) Concatenate all rows containing description into 1 variable adding vbNewLine in between and store it in description field.
2) More relational but also more complex - create 2nd table for description with PK as i.e. autonumber, ForeignKey Code referring to main table. Maintenance will be here very complex. Not really worth effort.
Amount of changes in code is quite big, so sorry I'll not provide fixed code but I hope idea is clear.
BTW: The reason why description is not updated is described in your post. You are increasing id only when code is present, so every description field from first group have id = 1. The most simple fix in your code would be to create 2 update statements - One for rows with code
UPDATE Voice SET Description = '" + v.Description + "' WHERE id= '"+id+"'
Second one for rows without code:
UPDATE Voice SET Description = Description + CHAR(13) + CHAR(10) + '" + v.Description + "' WHERE id= '"+id+"'

Related

Is it possible to populate a Farpoint Spread 6.0 vaSpread component using a SQL query in VB6?

I have written a query using T-SQL on SQL Server 2008 R2 that provides the correct information that I need to display on a vaSpread component named SSlist on Visual Basic 6. I have already opened the connection to the database, but I am having difficulty finding resources on how to populate the vaSpread component directly using my T-SQL query. I just need to display it exactly as how it shows up when I execute it in Microsoft SQL Server Management Studio.
My query is:
SELECT QC.LINE_CD AS 'Line Code', QC.LINE_NM AS 'Line Name', PN.GUBUN, WO.WRK_QTY AS 'Work QTY', CM.LINE_TARGET AS 'Line Target',
CM.RETURN_TARGET AS 'Return Target', SUM(PN.R_QTY) AS 'Rework QTY', SUM(PN.S_QTY) AS 'Scrap QTY',
SUM(PN.UPRC_AMT) AS 'UPRC AMT', (SUM(COALESCE(PN.UPRC_AMT,0)*PN.S_QTY)+SUM(PN.R_QTY)*3.8) AS 'Cost'
FROM QC_LINE_MST AS QC
LEFT JOIN (SELECT PE.LINE_CD, PE.WRK_YMD, PE.CUST_CD, PE.GUBUN, PE.ITMNO, PE.R_QTY, PE.S_QTY, ND.UPRC_AMT FROM PROC_ERR AS PE
INNER JOIN (SELECT ITMNO, CUST_CD, UPRC_AMT FROM NOW_DANGA) AS ND ON PE.ITMNO = ND.ITMNO AND PE.CUST_CD = ND.CUST_CD
WHERE PE.WRK_YMD BETWEEN '20161116' AND '20161201' AND (PE.R_QTY <> 0 OR PE.S_QTY <> 0)
) AS PN ON QC.LINE_CD = PN.LINE_CD
LEFT JOIN (SELECT A.CODE, A.DSCP AS LINE_TARGET, B.DSCP AS RETURN_TARGET FROM COD_MST AS A
INNER JOIN (SELECT CODE, DSCP FROM COD_MST WHERE GUBN='QC09'
) AS B ON A.CODE = B.CODE
WHERE A.GUBN='QC08') CM ON QC.LINE_CD = CM.CODE
LEFT JOIN (SELECT LINE_CD, SUM(WRK_QTY) AS WRK_QTY FROM WRK_ORD
WHERE WRK_YMD BETWEEN '20161116' AND '20161201' GROUP BY LINE_CD
) AS WO ON QC.LINE_CD = WO.LINE_CD
GROUP BY QC.LINE_CD, QC.LINE_NM, WO.WRK_QTY, PN.GUBUN, CM.LINE_TARGET, CM.RETURN_TARGET
ORDER BY QC.LINE_CD
I've searched online trying to figure out how to populate my vaSpread using this query, but either I am looking in the wrong place, or resources on Farpoint Spread 6.0 are scarce. If anyone has any ideas on how to implement this, or could direct me towards some helpful literature it would be much appreciated. Also, if anyone has any ideas on how to clean up my SQL
query and make it more efficient, that's welcome as well. I'm pretty new to this. Thank you, and let me know if I need to provide any more information! I look forward to reading your suggestions.
After doing some more research, I learned that instead of using the FarPoint 6.0 vaSpread component (non-OLEDB), the FarPoint 6.0 FpSpread component (OLEDB capable) should be used in order to automatically populate the spread sheet. However, the method to automatically populate the new FpSpread component required:
1) an ADODC component connected to the database
2) a stored procedure on the database
Seeing as how I already had an active connection and also needed to use certain column records in calculations to populate other columns, I decided to go with a manual spreadsheet population method using FOR loops. My code is attached below so that anyone having any similar issues can use my code for ideas.
With SSlist
//SQL Query to USA_ERP.QC_LINE_MST Table to receive total number of Rows in Record Set
SqlStmt = CSQL("SELECT COUNT(*) AS 'Count' FROM QC_LINE_MST")
Rs.Open SqlStmt, CN, adOpenForwardOnly, adLockReadOnly
LastRow = Val(Rs.Fields("Count"))
RowB4Last = Val(Rs.Fields("Count")) - 1
.MaxRows = LastRow
Rs.Close
//Formatting for Last Row (Totals row)
For RowCount = 1 To LastRow
.Row = RowCount
.RowHeight(.Row) = 18
//Font and cell formatting for Line Columns
For ColCount = 1 To 1
.Col = ColCount
.CellType = CellTypeStaticText
.TypeHAlign = TypeHAlignCenter
.FontBold = True
.TypeVAlign = TypeVAlignCenter
Next
If .Row = LastRow Then
//Merge for Totals label of Last Row (Totals row)
For ColCount = 1 To 2
.Col = ColCount
.Text = "Totals"
.RowMerge = MergeRestricted
Next
//Font and cell formatting for Last Row (Totals row)
For ColCount = 1 To 15
.Col = ColCount
.CellType = CellTypeStaticText
.TypeHAlign = TypeHAlignCenter
.FontBold = True
.TypeVAlign = TypeVAlignCenter
Next
End If
Next
//Main SQL Query to USA_ERP Database
SqlStmt = CSQL("SELECT QC.LINE_CD AS 'Line Code', QC.LINE_NM AS 'Line Name', PN.GUBUN, WO.WRK_QTY AS 'Work QTY', CM.LINE_TARGET AS 'Line Target', " & _
"CM.RETURN_TARGET AS 'Return Target', SUM(PN.R_QTY) AS 'Rework QTY', SUM(PN.S_QTY) AS 'Scrap QTY', " & _
"SUM(PN.UPRC_AMT) AS 'UPRC AMT', (SUM(COALESCE(PN.UPRC_AMT,0)*PN.S_QTY)+SUM(PN.R_QTY)*3.8) AS 'Cost' " & _
"FROM QC_LINE_MST AS QC " & _
"LEFT JOIN (SELECT PE.LINE_CD, PE.WRK_YMD, PE.CUST_CD, PE.GUBUN, PE.ITMNO, PE.R_QTY, PE.S_QTY, ND.UPRC_AMT FROM PROC_ERR AS PE " & _
"INNER JOIN (SELECT ITMNO, CUST_CD, UPRC_AMT FROM NOW_DANGA) AS ND ON PE.ITMNO = ND.ITMNO AND PE.CUST_CD = ND.CUST_CD " & _
"WHERE PE.WRK_YMD BETWEEN '$S' AND '$S' AND (PE.R_QTY <> 0 OR PE.S_QTY <> 0) " & _
") AS PN ON QC.LINE_CD = PN.LINE_CD " & _
"LEFT JOIN (SELECT A.CODE, A.DSCP AS LINE_TARGET, B.DSCP AS RETURN_TARGET FROM COD_MST AS A " & _
"INNER JOIN (SELECT CODE, DSCP FROM COD_MST WHERE GUBN='QC09' " & _
") AS B ON A.CODE = B.CODE " & _
"WHERE A.GUBN='QC08') CM ON QC.LINE_CD = CM.CODE " & _
"LEFT JOIN (SELECT LINE_CD, SUM(WRK_QTY) AS WRK_QTY FROM WRK_ORD " & _
"WHERE WRK_YMD BETWEEN '$S' AND '$S' GROUP BY LINE_CD " & _
") AS WO ON QC.LINE_CD = WO.LINE_CD " & _
"GROUP BY QC.LINE_CD, QC.LINE_NM, WO.WRK_QTY, PN.GUBUN, CM.LINE_TARGET, CM.RETURN_TARGET " & _
"ORDER BY QC.LINE_CD " _
, Format(DTPDate(0).Value, "YYYYMMDD"), Format(DTPDate(1).Value, "YYYYMMDD"), Format(DTPDate(0).Value, "YYYYMMDD"), Format(DTPDate(1).Value, "YYYYMMDD"))
Rs.Open SqlStmt, CN, adOpenForwardOnly, adLockReadOnly
While Not Rs.EOF
//Start at First Row for First Record from RecordSet (Rs), loop through all Records from RecordSet (Rs)
For RowCount = 1 To LastRow
.Row = RowCount
//Initialize/Re-initialize calculation variables for every Record
LineScrap = 0
CustomerScrap = 0
ResidentScrap = 0
ReworkQTY = 0
FailCost = 0
//Check to see if LastRow (Totals Row)
If .Row = LastRow Then
//If LastRow, populate columns with Total values
For ColCount = 1 To 15
.Col = ColCount
If .Col = 1 Then
ElseIf .Col = 2 Then
.ColMerge = MergeRestricted
ElseIf .Col = 3 Then
.Text = TotalProduction
ElseIf .Col = 4 Then
.Text = Val(Rs.Fields("Line Target"))
ElseIf .Col = 5 Then
.Text = TotalRework
ElseIf .Col = 6 Then
.Text = TotalScrap
ElseIf .Col = 7 Then
.Text = TotalReworkPPM
ElseIf .Col = 8 Then
.Text = TotalScrapPPM
ElseIf .Col = 9 Then
.Text = TotalFailCosts
ElseIf .Col = 10 Then
.Text = Val(Rs.Fields("Return Target"))
ElseIf .Col = 11 Then
.Text = TotalCustReturn
ElseIf .Col = 12 Then
.Text = TotalOnSiteReturn
ElseIf .Col = 13 Then
.Text = TotalCustReturnPPM
ElseIf .Col = 14 Then
.Text = TotalOnSiteReturnPPM
ElseIf .Col = 15 Then
.Text = TotalScrapPPM
Else
End If
Next
//Close database connection
Rs.Close
//Exit Subroutine logic
Exit Sub
End If
//Choose the correct variable to store "Scrap QTY" value from RecordSet (Rs) based on "GUBUN" value of Record
If IsNull(Rs.Fields("Scrap QTY")) = False Then
If Trim(Rs.Fields("GUBUN")) = "Customer" Then
CustomerScrap = Val(Rs.Fields("Scrap QTY"))
ElseIf Trim(Rs.Fields("GUBUN")) = "On Site" Then
ResidentScrap = Val(Rs.Fields("Scrap QTY"))
ElseIf Trim(Rs.Fields("GUBUN")) = "MIP NG" Then
LineScrap = Val(Rs.Fields("Scrap QTY"))
End If
//If "Scrap QTY" is NULL then set correct variable to 0 based on "GUBUN" value of Record
Else
If Trim(Rs.Fields("GUBUN")) = "Customer" Then
CustomerScrap = 0
ElseIf Trim(Rs.Fields("GUBUN")) = "On Site" Then
ResidentScrap = 0
Else
LineScrap = 0
End If
End If
//Store "Rework QTY" in correct variable
//If "Rework QTY" is NULL, store 0
If IsNull(Rs.Fields("Rework QTY")) = False Then
ReworkQTY = Val(Rs.Fields("Rework QTY"))
Else
ReworkQTY = 0
End If
//Populate spread (SSList) with correct values using RecordSet (Rs) and calculated variables
//Line Column
.Col = 1
.Text = Rs.Fields("Line Code")
//Model Column
.Col = 2
.Text = Rs.Fields("Line Name")
//Prod (EA) Column
.Col = 3
//If "Work QTY" Record is Null set cell value to 0
If IsNull(Rs.Fields("Work QTY")) = False Then
.Text = Trim(Val(Rs.Fields("Work QTY")) + LineScrap)
Else
.Text = 0
End If
//Calculate running total for 'Prod (EA)' Column through all Records/loops
TotalProduction = TotalProduction + Val(.Text)
//In Line Target (PPM) Column
.Col = 4
//If "Line Target" Record is Null set cell value to 0
If IsNull(Rs.Fields("Line Target")) = False Then
.Text = Trim(Val(Rs.Fields("Line Target")))
Else
.Text = 0
End If
//In Line Rework QTY Column
.Col = 5
//If "Rework QTY" Record is Null set cell value to 0
If IsNull(Rs.Fields("Rework QTY")) = False Then
.Text = ReworkQTY
Else
.Text = 0
End If
//Calculate running total for 'In Line Rework QTY' Column through all Records/loops
TotalRework = TotalRework + Val(.Text)
//In Line Scrap QTY Column
.Col = 6
//Set cell value to LineScrap variable
.Text = LineScrap
//Calculate running total for 'In Line Scrap QTY' Column through all Records/loops
TotalScrap = TotalScrap + Val(.Text)
//In Line Rework PPM QTY Column
.Col = 7
//If "Work QTY" Record is Null set cell value to 0
If IsNull(Rs.Fields("Work QTY")) = False Then
.Text = Round(ReworkQTY / (Val(Rs.Fields("Work QTY")) + LineScrap) * 10 ^ 6, 6)
Else
.Text = 0
End If
//Calculate running total for 'In Line Rework PPM QTY' Column through all Records/loops
TotalReworkPPM = TotalReworkPPM + Val(.Text)
//In Line Scrap PPM QTY Column
.Col = 8
//If "Work QTY" is Null set cell value to 0
If IsNull(Rs.Fields("Work QTY")) = False Then
.Text = Round(LineScrap / (Val(Rs.Fields("Work QTY")) + LineScrap) * 10 ^ 6, 6)
Else
.Text = 0
End If
//Calculate runing total for 'In Line Scrap PPM QTY' Column through all Records/loops
TotalScrapPPM = TotalScrapPPM + Val(.Text)
//In Line Fail Costs ($) Column
.Col = 9
//If "GUBUN" Record is "MIP NG" and "Cost" Record is Not Null set cell value to "Cost" Record
//Otherwise, set cell value to 0
If Trim(Rs.Fields("GUBUN")) = "MIP NG" Then
If IsNull(Trim(Rs.Fields("Cost"))) = False Then
.Text = Val(Rs.Fields("Cost"))
Else
.Text = 0
End If
Else
.Text = 0
End If
//Calculate running total for 'In Line Fail Costs ($)' Column through all Records/loops
TotalFailCosts = TotalFailCosts + Val(.Text)
//Customer Return Target PPM QTY Column
.Col = 10
//If "Return Target" Record is Null set cell value to 0
If IsNull(Rs.Fields("Return Target")) = False Then
.Text = Trim(Val(Rs.Fields("Return Target")))
Else
.Text = 0
End If
//Customer Return QTY Column
.Col = 11
//Set cell value to CustomerScrap variable
.Text = CustomerScrap
//Calculate running total for 'Customer Return QTY' Column through all Records/loops
TotalCustReturn = TotalCustReturn + Val(.Text)
//On Site Return QTY Column
.Col = 12
//Set cell value to ResidentScrap variable
.Text = ResidentScrap
//Calculate running total for 'On Site Return QTY' Column through all Records/loops
TotalOnSiteReturn = TotalOnSiteReturn + Val(.Text)
//Customer Return PPM QTY Column
.Col = 13
//If "Work QTY" Record is Null set cell value to 0
If IsNull(Rs.Fields("Work QTY")) = False Then
.Text = Round(CustomerScrap / (Val(Rs.Fields("Work QTY")) + LineScrap) * 10 ^ 6, 2)
Else
.Text = 0
End If
//Calculate running total for 'Customer Return PPM QTY' Column through all Records/loops
TotalCustReturnPPM = TotalCustReturnPPM + Val(.Text)
//On Site Return PPM QTY Column
.Col = 14
//If "Work QTY" Record is Null set cell value to 0
If IsNull(Rs.Fields("Work QTY")) = False Then
.Text = Round(ResidentScrap / (Val(Rs.Fields("Work QTY")) + LineScrap) * 10 ^ 6, 2)
Else
.Text = 0
End If
//Calculate running total for 'On Site Return PPM QTY' Column through all Records/loops
TotalOnSiteReturnPPM = TotalOnSiteReturnPPM + Val(.Text)
//Total Loss PPM Column
.Col = 15
//If "Work QTY" Record is Null set cell value to 0
If IsNull(Rs.Fields("Work QTY")) = False Then
.Text = Round((CustomerScrap + LineScrap) / (Val(Rs.Fields("Work QTY")) + LineScrap) * 10 ^ 6, 0)
Else
.Text = 0
End If
//Calculate running total for 'Total Loss PPM' Column through all Records/loops
TotalLossPPM = TotalLossPPM + Val(.Text)
//Move to the next Record in RecordSet (Rs)
Rs.MoveNext
Next
Wend
End With
This code is run with an active connection to a database, CN, with a RecordSet, Rs. The FOR loop basically goes through every column of every row and populates each cell with the correct values needed based on the logic, moving to the next Record in the RecordSet after every row. The last row in my SQL query RecordSet is a totals row that has data only in certain columns. When reaching this last row, it populates the cells with either the calculated running totals or, when available, the values in the RecordSet. After populating the last row of the table, the subroutine ends.
I don't know if anyone has any interest in this problem, but hopefully this can help someone. This may not be the ideal or most efficient way of populating a FarPoint vaSpread component, but it works 100% of the time and depending on your SQL query you can make this future proof. In particular, I have my query set up so all of the joins occur on a single reference table (QC.LINE_MST) populated with line codes or "Line_CD"'s that I would like to see on the table. This enables me to just add new "Line_CD"'s to that reference table so that my query and thus my program will pick it up on the next inquiry. This logic also handles NULL values from the SQL table, setting all NULL values to 0 before any calculations are made or cells are populated. The only time that this logic needs to be updated is when you would like to add new information columns to the table, something that I personally won't need to do.
If anyone has any suggestions for the code, ways to make it more efficient or have cleaner formatting, please leave a comment below.

Working out a basic score from integer values

I'm trying to work out a basic % value by gathering values together:
For Each M As Match In matchFound
lamdaFix2 = M.Groups(1).Value
lamdaFix3 = M.Groups(2).Value
Application.DoEvents()
Dim lv As ListViewItem = formMozCheck.listViewMoz.Items.Add(lamdaFix1)
lv.UseItemStyleForSubItems = False
lv.SubItems.Add(Math.Round(Double.Parse(lamdaFix2)).ToString())
lv.SubItems.Add(Math.Round(Double.Parse(lamdaFix3)).ToString())
lv.SubItems.Add("-")
lv.SubItems.Add("-")
lv.SubItems.Add(itm.SubItems(8).Text)
Dim srVal As Integer
If (itm.SubItems(9).Text = "") Then
srVal = 0
Else
srVal = CInt(itm.SubItems(9).Text)
End If
lv.SubItems.Add(srVal.ToString())
' work out a score
Dim overAllScore As Integer
' TODO: basic score
overAllScore = CInt(CInt(CDbl(Math.Round(Double.Parse(lamdaFix2)).ToString()) & CDbl(Math.Round(Double.Parse(lamdaFix3)).ToString()) & CDbl(itm.SubItems(8).Text) & Val(srVal)) * 100)
lv.SubItems.Add(CLng(overAllScore) & "%").ForeColor = Color.DarkGreen
itm.Checked = False
Next
These values:
lv.SubItems.Add(Math.Round(Double.Parse(lamdaFix2)).ToString())
lv.SubItems.Add(Math.Round(Double.Parse(lamdaFix3)).ToString())
Are values between 0 - 100
And these ones:
itm.SubItems(8).Text
itm.SubItems(9).Text
Are values between 1 - 10
I have been racking the brains to see what the best way to add these values up and give a basic percentage, my attempt:
overAllScore = CInt(CInt(CDbl(Math.Round(Double.Parse(lamdaFix2)).ToString()) & CDbl(Math.Round(Double.Parse(lamdaFix3)).ToString()) & CDbl(itm.SubItems(8).Text) & Val(srVal)) * 100)
Just adds all values like 234524 rather than the total value of 23+45+2+4
i'm probably over complicating this lol
i tagged it as both vb and c# as i though the logic would be the same ;)
thanks for any help guys!
Graham
You should use "+" instead of "&":
overAllScore = CInt(CInt(CDbl(Math.Round(Double.Parse(lamdaFix2)).ToString()) + CDbl(Math.Round(Double.Parse(lamdaFix3)).ToString()) + CDbl(itm.SubItems(8).Text) + Val(srVal)) * 100)

How to merge cells and remove blank spaces in my DataGrid using proper loop

My title is still broad so i'll explain here further.
This is my current output using my code:
.
But I want to make it look like this..
As you can see on the pictures, i want to remove the blank spaces. Because if I selected MORE data, let's say I selected 7 more days, it will go DIAGONALLY not horizontally.
I think I have a problem regarding my loops. Hope you can help me trace because I've been stuck here for a week debugging. (nevermind my long query, i just want to post all my code. I've also added comments for easier debugging.)
Here's my code:
Private Sub LoadDateAndUser()
Dim SqlStr As String = ""
Dim sqlConn As New SqlConnection(DataSource.ConnectionString)
Dim sqlComm As New SqlCommand(SqlStr, sqlConn)
Dim sqlAdapter As New SqlDataAdapter(sqlComm)
Dim o_Dataset As New DataSet()
SqlStr = " SELECT convert(varchar(10), A.TransDate, 101) as TransDate,ADMMED.TransNum, ADMMED.AdministeredDate, D.Dosage [Dosage], ISNULL(C.GenericName, ' ') + ' (' + IsNull(B.ItemName,'') + ' ' + IsNull(B.ItemDesc,'') + ')' [Medication], ADMMED.UserID" & _
" FROM INVENTORY..tbInvStockCard as A" & _
" LEFT OUTER JOIN INVENTORY..tbInvMaster as B On A.ItemID = B.ItemID " & _
" LEFT OUTER JOIN Inventory.dbo.tbForGeneric as C On B.GenericID = C.GenericID" & _
" LEFT OUTER JOIN Station..tbNurse_AdministeredMedicines ADMMED on a.idnum= ADMMED.idnum " & _
" LEFT OUTER JOIN build_file.dbo.tbCoDosage as D on A.DosageID = D.DosageID" & _
" LEFT OUTER JOIN Station.dbo.tbNurseCommunicationFile as E on A.IdNum = E.IDnum and E.ReferenceNum = A.RefNum" & _
" WHERE A.IdNum = '" & Session.Item("IDNum") & "' and ( A.RevenueID = 'PH' or A.RevenueID = 'PC' ) " & _
" AND A.LocationID = '20' and Not IsNull(ADMMED.AdministeredDate, '') = ''" & _
" AND A.RefNum = ADMMED.ReferenceNum and ADMMED.ItemID = A.itemid" & _
" AND (B.ItemClassificationID = '1' or B.ItemClassificationID = '10' or B.ItemClassificationID = '11' or B.ItemClassificationID = '16' or B.ItemClassificationID = '2' or B.ItemClassificationID = '9')" & _
" order by TransDate desc,ADMMED.AdministeredDate desc"
sqlComm.CommandText = SqlStr
sqlAdapter.Fill(o_Dataset, "Table")
Dim o_Row As DataRow
Dim o_AdmDates As New Collection()
Dim s_FormattedLastAdmDate As String = ""
Dim s_FormattedAdmDate As String = ""
Dim o_DerivedTable As New DataTable()
With o_DerivedTable
.Columns.Add("TransDate")
.Columns.Add("Medication")
.Columns.Add("Dosage")
.Columns.Add("TransNum")
End With
'Select all unformatted administered dates from the query
Dim o_UnformattedAdmDates As DataRow() = o_Dataset.Tables(0).Select("", "AdministeredDate Desc")
'Extract distinct administered dates and change its format
For Each o_Row In o_UnformattedAdmDates
s_FormattedAdmDate = Format(CDate(o_Row.Item("AdministeredDate")), KC_Date_Format) 'eg. Jan 01 15
If s_FormattedLastAdmDate <> s_FormattedAdmDate Then
s_FormattedLastAdmDate = s_FormattedAdmDate
o_AdmDates.Add(s_FormattedLastAdmDate) 'add all formatted dates in o_AdmDates
End If
Next
'Add formatted administred dates to derived table
Dim o_Item As String
For Each o_Item In o_AdmDates
o_DerivedTable.Columns.Add(o_Item)
Next
'Loop through the administred date
Dim o_NewRow As DataRow
Dim o_NextRow As DataRow
Dim i_Ctr As Integer
Dim x_isNewRow As Boolean = True
Dim i_MaxRec As Integer
i_MaxRec = o_Dataset.Tables(0).Rows.Count - 1
For i_Ctr = 0 To i_MaxRec
o_Row = o_Dataset.Tables(0).Rows(i_Ctr)
If i_Ctr <> i_MaxRec Then
o_NextRow = o_Dataset.Tables(0).Rows(i_Ctr + 1)
End If
If x_isNewRow Then
o_NewRow = o_DerivedTable.NewRow()
End If
o_NewRow("TransDate") = o_Row("TransDate")
o_NewRow("Medication") = o_Row("Medication")
o_NewRow("Dosage") = o_Row("Dosage")
o_NewRow("TransNum") = o_Row("TransNum")
'Fill approriate result date column based on query
For Each o_Item In o_AdmDates
s_FormattedAdmDate = Format(CDate(o_Row.Item("AdministeredDate")), KC_Date_Format)
Dim AdmTim As DateTime = DateTime.Parse(o_Row("AdministeredDate"))
If s_FormattedAdmDate = o_Item Then
o_NewRow(s_FormattedAdmDate) = AdmTim.ToString("hh:mm tt") + " - " + o_Row("UserID")
End If
Next
If i_Ctr < i_MaxRec _
And Not o_NextRow Is Nothing _
And o_Row("TransDate") = o_NextRow("TransDate") _
And o_Row("Medication") = o_NextRow("Medication") _
And o_Row("Dosage") = o_NextRow("Dosage") _
And o_Row("AdministeredDate") = o_NextRow("AdministeredDate") Then
x_isNewRow = False
Else
o_DerivedTable.Rows.Add(o_NewRow)
x_isNewRow = True
End If
Next
'Bind derived table
dgSheet.DataSource = o_DerivedTable
dgSheet.DataBind()
If o_Dataset.Tables(0).Rows.Count > 0 Then
GroupGridView(dgSheet.Items, 0, 3)
Else
End If
End Sub
I think you must review your programming logic:
After that huge ugly SqlStr : you will have a DataSet, with a Table with all rows mixed !?
Let's try a pseudo-code:
I think is better to create in that DataSet, 2 Tables:<br>
**first** table with: id, DateOrder, Medication, Dosage <br>
and **second** table with: idDate, FirstTable.id, AdministeredDate
after that you know how many ADMMED.AdministeredDate.Count are, because you must know how manny columns you need to add
create a 3-rd table from iteration of first table, nested with second by ID.
Set as Datasource for DataGridView the Third DataTable.
So you have 2 datasets, and generate this one .. one to many ..
.. I have no time now, if you don't get the ideea .. forget it !

VB.net Auto Newline After Copying

First of all, I'm still new in VB.net and I had encountered one weird issue
I had created a tools that will split content from multilines textbox A into lines of string and add some characters and join them back and display in another multilines textbox B (A -> split content -> add character -> join -> display in B). The sample would be like this
Original Data from A:
This
is
a
test
data
Result Displayed in B:
Row 0 = This
Row 1 = is
Row 2 = a
Row 3 = test
Row 4 = data
Result COPIED from B:
Row 0 = This
Row 1 =
is
Row 2 =
a
Row 3 =
test
Row 4 =
data
The source code is
tempA = ""
tempB = ""
tempA = A.Text()
stringAry = tempA.Split(Environment.NewLine)
For iCounter As Integer = 0 To stringAry.Length - 1
tempB = tempB + "Row " + iCounter.ToString + " = " + stringAry(iCounter).ToString + Environment.NewLine
Next
B.Text() = tempB
So may I know why the copied result will be different from result displayed and how could I solve this?
You should remove any unwanted new line characters from the stringAry(iCounter) value.
tempA = ""
tempB = ""
tempA = A.Text()
stringAry = tempA.Split(Environment.NewLine)
For iCounter As Integer = 0 To stringAry.Length - 1
tempB = tempB + "Row " + iCounter.ToString + " = " + stringAry(iCounter).ToString.Replace(Environment.NewLine, string.Empty) + Environment.NewLine
Next
B.Text() = tempB

vb.net - How can I change the type of values that the DataTable can store?

I want to add characters (like % and pp) in values stored in a DataTable, but I'm getting an error message:
Input string was not in a correct format.Couldn't store <97.0%> in Actual Column. Expected type is Decimal.
How can I change the type of values that the DataTable can store?
Dim dv As New System.Data.DataView
Dim dt As New System.Data.DataTable
dv = SQL_Customer.Select(DataSourceSelectArguments.Empty)
dt = dv.ToTable()
dt.Rows(1)(1) = CStr(dt.Rows(1)(1)) & "%"
dt.Rows(1)(2) = CStr(dt.Rows(1)(2)) & "%"
dt.Rows(1)(3) = CStr(dt.Rows(1)(3)) & "%"
dt.Rows(1)(4) = CStr(dt.Rows(1)(4)) & "pp"
You can't change the type of a data table column once it's filled.
One work around is to add a new column of type string and then populate that column with the string values you need and then delete the column that is of the type you don't need.
If this helps someone, this is how I resolved the problem:
Dim dv As New System.Data.DataView
Dim dt As New System.Data.DataTable
Dim dt2 As New System.Data.DataTable
Dim SelectedIndex As Object
If datagrid.SelectedIndex = "-1" Then SelectedIndex = 0 Else SelectedIndex = GV_Cust.SelectedIndex
'Populate Dataview with data in SQL Query for Customer KPIs
dv = SQL_Customer.Select(DataSourceSelectArguments.Empty)
'Populate table with data from dataview. Note that the data is formated as per data loaded. So if number is loaded, then format for the cell is number. This creates a problem when adding percentages
dt = dv.ToTable()
'New colums are added as string format in the dataTable so that % and pp can be added
Dim column As DataColumn
For i = 1 To 6
' Create second column.
column = New DataColumn()
column.DataType = System.Type.GetType("System.String")
column.ColumnName = i
column.AutoIncrement = False
column.Caption = i
column.ReadOnly = False
column.Unique = False
' Add the Column to the DataColumnCollection.
dt.Columns.Add(column)
Next
'New columns are populated and calculations for variances are calculated
For j = 0 To 2
For i = 0 To 4
dt.Rows(i)(7 + j) = dt.Rows(i)(1 + j) & "%"
dt.Rows(i)(10) = (dt.Rows(i)(1) - dt.Rows(i)(2)) & "pp"
dt.Rows(i)(11) = (dt.Rows(i)(1) - dt.Rows(i)(3)) & "pp"
dt.Rows(i)(12) = (dt.Rows(i)(2) - dt.Rows(i)(3)) & "pp"
Next
For i = 5 To 6
dt.Rows(i)(7 + j) = dt.Rows(i)(1 + j)
If dt.Rows(i)(2) = 0 Then dt.Rows(i)(10) = 0 & "%" Else dt.Rows(i)(10) = Math.Round((((dt.Rows(i)(1) / dt.Rows(i)(2))) - 1) * 100, 1) & "%"
If dt.Rows(i)(3) = 0 Then dt.Rows(i)(11) = 0 & "%" Else dt.Rows(i)(11) = Math.Round((((dt.Rows(i)(1) / dt.Rows(i)(3))) - 1) * 100, 1) & "%"
If dt.Rows(i)(3) = 0 Then dt.Rows(i)(12) = 0 & "%" Else dt.Rows(i)(12) = Math.Round((((dt.Rows(i)(2) / dt.Rows(i)(2))) - 1) * 100, 1) & "%"
Next
Next
'Old columns are deleted and new wones are renamed
dt.Columns.Remove("A")
dt.Columns("1").ColumnName = "A"
dt.Columns.Remove("B")
dt.Columns("2").ColumnName = "B
dt.Columns.Remove("C")
dt.Columns("3").ColumnName = "C"
dt.Columns.Remove("D")
dt.Columns("4").ColumnName = "D"
dt.Columns.Remove("D")
dt.Columns("5").ColumnName = "E"
dt.Columns.Remove("F")
dt.Columns("6").ColumnName = "F"
'Customer grid is populated, a selection button is added and the first row is selected
datagrid.DataSource = dt
datagrid.AutoGenerateSelectButton = True
datagrid.DataBind()
datagrid.SelectedIndex = SelectedIndex