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

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.

Related

Update previous row

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+"'

Set Column BackColor in Datagridview to override Row BackColor in VB.net

working in vb.net in Visual Studio on a datagridview.
The rows are days of the week. The rows all alternate backcolor (variables LightColour1 and LightColour2), then the weekend rows are variable WeekendRowsColour. That's all easy enough, but now I have to make the entire final column white. But I can't seem to override the row colors no matter how I approach it. Any advice?
Here's my code section:
For r = 0 To 27
dgv.Rows.Add()
dgv.Rows(r).Cells(0).Value = Format(nDate, "ddd")
dgv.Rows(r).Cells(1).Value = Format(nDate, "d/MM/yyyy")
If Format(nDate, "ddd") = "Sat" Or Format(nDate, "ddd") = "Sun" Then
dgv.Rows(r).DefaultCellStyle.BackColor = WeekendRowsColour
dgv.Rows(r).DefaultCellStyle.SelectionBackColor = WeekendRowsSelColour
Else
If r Mod 2 = 0 Then 'even row
dgv.Rows(r).DefaultCellStyle.BackColor = LightColour1
dgv.Rows(r).DefaultCellStyle.SelectionBackColor = SelLightColour1
Else 'alternate row
dgv.Rows(r).DefaultCellStyle.BackColor = LightColour2
dgv.Rows(r).DefaultCellStyle.SelectionBackColor = SelLightColour2
End If
End If
nDate = DateAdd(DateInterval.Day, 1, nDate)
Next
dgv.Columns(dgv.Columns.Count - 1).DefaultCellStyle.BackColor = Color.White
But no matter how I approach it, the last column comes out the default color. My best success has been setting the backcolor and alternatingrowsbackcolor of the rows programmatically, and setting the column properties to white in the designer, but that doesn't overwrite the alternating rows or the weekend colors.
Pulling my hair out here!
You have to set it inside the loop per cell like this:
For r = 0 To 27
dgv.Rows.Add()
dgv.Rows(r).Cells(0).Value = Format(nDate, "ddd")
dgv.Rows(r).Cells(1).Value = Format(nDate, "d/MM/yyyy")
If Format(nDate, "ddd") = "Sat" Or Format(nDate, "ddd") = "Sun" Then
dgv.Rows(r).DefaultCellStyle.BackColor = WeekendRowsColour
dgv.Rows(r).DefaultCellStyle.SelectionBackColor = WeekendRowsSelColour
Else
If r Mod 2 = 0 Then 'even row
dgv.Rows(r).DefaultCellStyle.BackColor = LightColour1
dgv.Rows(r).DefaultCellStyle.SelectionBackColor = SelLightColour1
Else 'alternate row
dgv.Rows(r).DefaultCellStyle.BackColor = LightColour2
dgv.Rows(r).DefaultCellStyle.SelectionBackColor = SelLightColour2
End If
End If
nDate = DateAdd(DateInterval.Day, 1, nDate)
dgv.Rows(r).Cells(dgv.Columns.Count-1).Style.BackColor = Color.White
Next

Moving textbox output into a different textbox

I am trying to output text into another text box once the first has 5 entries in it. Example; i give the scores 100,200,300,200,200. Now when I try to enter a new score it should place it in the next textbox, but doesent.
Dim Testint As Integer ' define an Integer for testing
Dim sampleTextBox(3) As TextBox
sampleTextBox(0) = txtPlayer1Scores
sampleTextBox(1) = txtPlayer2Scores
sampleTextBox(2) = txtPlayer3Scores
sampleTextBox(3) = txtPlayer4Scores
Dim sampleLabel(3) As Label
sampleLabel(0) = lblPlayer1Average
sampleLabel(1) = lblPlayer2Average
sampleLabel(2) = lblPlayer3Average
sampleLabel(3) = lblPlayer4Average
scoreArray(textCount, gameNumber - 1) = CInt(txtScoreInput.Text) ' subtracting 1 from the score array
sampleTextBox(textCount).Text &= " Score:" & scoreArray(textCount, gameNumber - 1) & vbCrLf
'output statement
gameNumber = gameNumber + 1 'increment the counter
If gameNumber > MAX_SCORE_LENGTH Then
sampleTextBox(textCount).Focus()
sampleTextBox(textCount).Enabled = False
For i As Integer = 0 To 4 'Add the array values up
scoreTotal += scoreArray(textCount, i)
Next
playerAverage = scoreTotal / MAX_SCORE_LENGTH
sampleLabel(labelCount).Text = playerAverage
' I need the textbox switch here
textCount = textCount + 1
labelCount = labelCount + 1 ' and labels
ElseIf textCount > MAX_PLAYERS Then
'calculate team average
btnEnterScore.Enabled = False
Else
lblEnterScore.Text = "Enter Score for game #" & gameNumber ' 5 scores have not be inputted,
txtScoreInput.Text = "" 'ask for more
txtScoreInput.Focus() 'refocus the input textbox
End If
Fixed it...setting the max length to 15 forces it to move on after 15 digits, it also works when there are less than 15 digits
txtscore1.MaxLength = 15

Issues with For Loop in VB

For i = 1 To 5
If i = 0 Then
i = i + 1
ElseIf i Mod 2 = 0 Then
LabelEvens.Text = i
i = i + 1
Else
LabelOdds.Text = i
i = i + 1
End If
Next i
I'm making a program in VB where I have to use a for loop to sort between 2 numbers(loop limit 1 and 2) and find if they are even or odd, Then output the results to 2 labels. This loop makes sense to me, but for example when I put in 1 and 4 all it outputs is a 5 in the odd label. I guess my question is can anyone see the issue with my loop?
You don't need to add 1 to your loop variable i manually, the for loop itself does that for you behind the scenes:
For i = 1 To 5
If i Mod 2 = 0 Then
LabelEvens.Text = i
Else
LabelOdds.Text = i
End If
Next i
You'll noticed I've also removed the If i = 0 bit since i can never be zero within that loop. It ranges from one to five inclusive.
One other thing you'll need to do is to append the value to your text box. What you have at the moment is a replacement so that it'll only be set to the last value processed. Something like this should suffice:
' Initialise to empty strings '
LabelEvens.Text = ""
LabelOdds.Text = ""
' Append the values '
For i = 1 To 5
If i Mod 2 = 0 Then
LabelEvens.Text = LabelEvens.Text & "," & CStr(i)
Else
LabelOdds.Text = LabelOdds.Text & "," & CStr(i)
End If
Next i
' Remove initial comma from both '
LabelEvens.Text = Mid(LabelEvens.Text,2)
LabelOdds.Text = Mid(LabelOdds.Text,2)
Some issues in your code:
For i = 1 To 5
If i = 0 Then <-- 'I' will never be 0 since you start from 1
i = i + 1 <-- Don't manually increment since you are using a for
ElseIf i Mod 2 = 0 Then
LabelEvens.Text = i
i = i + 1 <-- Don't manually increment since you are using a for
Else
LabelOdds.Text = i
i = i + 1 <-- Don't manually increment since you are using a for
End If
Next i
Another issue you have is that if you have more than one odd number in the for range (say in a range of 1 to 10) you will only get the last number. What do you want to do in this case? Concatenate all odd numbers in a string or stop after the first one is found? Do you really need a FOR loop at all?
you can Also state
LabelEvens.Text="" 'Clear contents of the label before assigning new values
LabelOdds.Text=""
For i As Integer = 1 To 5
If i Mod 2 = 0 Then
LabelEvens.Text = LabelEvens.Text & i
Else
LabelOdds.Text = LabelOdds.Text & i
End If
Next
From Above you can replace '&' with '+' if you want the Total.

inner loops, procedure call confusion

So what the issue is, i have 2 for loops one nested within another. The outer loop calling a procedure, the inner loop setting a attribute for the procedure to use. The problem is that the procedure is that I wan't to exit the loop use the pos <-- attribute call the procedure and re-enter the inner loop. At the minute the pos is only being set once because all the conditions are true within the inner loop meaning that its being replaced each time. I want to be able to set the pos exit the inner loop, call the procedure and re-enter the inner loop and set it pos to a different value? any help would be great!! here is the code
For Each val As String In vals
If creditPoints = "20" And semester = "1" And year = "Year 1" Then
For Each position In MyPosList
If position.strLabel = "a1" And available(0) <> "False" Then
pos = position.strX & " " & position.strY
count += 1
available(0) = blnavailable
ElseIf position.strLabel = "b1" And available(1) <> "False" Then
pos = position.strX & " " & position.strY
count += 1
available(1) = blnavailable
Next
shortfat(semester, pos, creditPoints, title, year, modStatus, count)
End If
next
Are you just looking to break out of the inner loop when one of those conditions are met? If so, that's what the Exit keyword is for. You really should also set a flag to sanity check yourself, too.
''//Flag so that we know if we actually found a position
Dim FoundPosition as Boolean
For Each val As String In vals
''//Reset the flag and assume that are conditions are met
FoundPosition = False
If creditPoints = "20" And semester = "1" And year = "Year 1" Then
For Each position In MyPosList
If position.strLabel = "a1" And available(0) <> "False" Then
pos = position.strX & " " & position.strY
count += 1
available(0) = blnavailable
''//Flag that our conditions are met
FoundPosition = True
''//Exit from the inner loop
Exit For
ElseIf position.strLabel = "b1" And available(1) <> "False" Then
pos = position.strX & " " & position.strY
count += 1
available(1) = blnavailable
''//Flag that our conditions are met
FoundPosition = True
''//Exit from the inner loop
Exit For
End If
Next
''//Sanity check to ensure that our conditions are met
If FoundPosition Then
shortfat(semester, pos, creditPoints, title, year, modStatus, count)
Else
''//Do something here, either Throw an error or safely handle this case otherwise
End If
End If
Next
"I want to be able to set the pos exit the inner loop, call the
procedure and re-enter the inner loop and set it pos to a different
value?"
Things like that are better served with a WHILE loop than a FOR loop.
Just a stab in the dark here, but it sounds like you want to be able to see if shortfat is producing a favorable value. And if it does not, you want it to recompute pos. The first thing I'd do, is alter shortfat to return some kind of value...for my example, I'll have it return a boolean.
Dim blnDidThisDoWhatIWant As Boolean
For Each val As String In vals
If creditPoints = "20" And semester = "1" And Year() = "Year 1" Then
blnDidThisDoWhatIWant = False
While blnDidThisDoWhatIWant = False
For Each position In MyPosList
If position.strLabel = "a1" And available(0) <> "False" Then
pos = position.strX & " " & position.strY
count += 1
available(0) = blnavailable
ElseIf position.strLabel = "b1" And available(1) <> "False" Then
pos = position.strX & " " & position.strY
count += 1
available(1) = blnavailable
End If
Next
blnDidThisDoWhatIWant = shortfat(semester, pos, creditPoints, title, Year, modStatus, count)
End While
End If
Next
This will allow you to re-enter the inner loop. The problem is that it'll be infinite unless pos is computed differently (which I don't see how it can). So that's something you'll have to work out on your own. Hope this helps point you in the right direction.