Using a Case statement with an Int entry from a table - vb.net

What is the best way to compare an Int entry from a table in a case statement?
Using SQL server 2008 R2, Visual Basic Express with LINQ to SQL.
The code I tried doesnt work:
Private Sub UpdateSetOpt()
Dim db = New ACEDataContext
Dim SRM = From q In db.Settings
Where q.SettingID = frmMain.CurrentSID
Select q.RollMethod
Select Case SRM
Case 1
rbStandard.Checked = True
Case 2
rbProfession.Checked = True
Case 3
rbSpecies.Checked = True
Case 4
rbRandom.Checked = True
Case Else
rbStandard.Checked = False
rbProfession.Checked = False
rbSpecies.Checked = False
rbRandom.Checked = False
End Select
End Sub

SRM isn’t an Integer since your From query returns a collection of items. To get just the first, use Single():
Dim SRM = (From q In db.Settings
Where q.SettingID = frmMain.CurrentSID
Select q.RollMethod).Single()
If the query actually returns more than a single value the above code will fail; you need to use First instead of Single then. Both will fail if no value is returned by the query. In that case, FirstOrDefault may be used instead (but probably isn’t appropriate in your situation).
Adding to that, your Select Case is a sign of code smell. You should rather create an array of all the check boxes and use the integer to map into it:
Dim checks As CheckBox() = New CheckBox() { _
rbStandard, rbProfession, rbSpecies, rbRandom }
' Unset all checkboxes:
For Each check In checks
check.Checked = False
End For
If SRM > 0 AndAlso SRM <= checks.Length Then
checks(SRM - 1).Checked = True
End If

SRM in your case is not an int but IEnumerabe<int>.
You want the first element:
SELECT CASE SRM.FirstOrDefault():

Related

Access crosstab query data parameter not filtering query

I have finally got my crosstab report to dynamically update but for some reason the date parameters are not passing to either the report or the query.
I have a recordset updating the crosstab report and on hover/step through the date parameter in vba is showing the correct date but the report is still showing all data.
The query is also showing data for all dates. Is it something I have done wrong in the query? I have tried every option I could find in what seems like every forum and just can't get a solution.
This is the SQL for the query
PARAMETERS [Forms]![frm_menu]![txtFromDate] DateTime,
[Forms]![frm_menu]![txtToDate] DateTime,
[Forms]![frm_menu]![cmbMplTag1] Text ( 255 ),
[Forms]![frm_menu]![cmbMplTag2] Text ( 255 ),
[Forms]![frm_menu]![cmbMplTag3] Text ( 255 ),
[Forms]![frm_menu]![cmbMplTag4] Text ( 255 ),
[Forms]![frm_menu]![cmbMplTag5] Text ( 255 );
TRANSFORM First(tbl_logdata.Input_Value) AS FirstOfInput_Value
SELECT tbl_logdata.Log_Date, tbl_logdata.Log_Time
FROM tbl_logdata
WHERE (((tbl_logdata.Log_Date) Between [Forms]![frm_menu]![txtFromDate]
And [Forms]![frm_menu]![txtToDate])
AND ((tbl_logdata.tag)=[Forms]![frm_menu]![cmbMplTag1]))
OR (((tbl_logdata.tag)=[Forms]![frm_menu]![cmbMplTag2]))
OR (((tbl_logdata.tag)=[Forms]![frm_menu]![cmbMplTag3]))
OR (((tbl_logdata.tag)=[Forms]![frm_menu]![cmbMplTag4]))
OR (((tbl_logdata.tag)=[Forms]![frm_menu]![cmbMplTag5]))
GROUP BY tbl_logdata.Log_Date, tbl_logdata.Log_Time
PIVOT tbl_logdata.tag;
And this is the VBA for the crosstab report. The parameters for the cmbMplTag# are working fine:
Private Sub Report_Open(Cancel As Integer)
Dim rst As dao.Recordset
Dim db As dao.Database
Dim qdf As dao.QueryDef
Dim i As Integer
Dim j As Integer
Set db = CurrentDb
Set qdf = db.QueryDefs("qry_MplTagsSummary")
'on hover shows date from textbox'
qdf.Parameters("Forms!frm_menu!txtFromDate") = [Forms]![frm_menu]![txtFromDate]
'on hover shows date from textbox'
qdf.Parameters("Forms!frm_menu!txtToDate") = [Forms]![frm_menu]![txtToDate]
qdf.Parameters("[Forms]![frm_menu]![cmbMplTag1]") = [Forms]![frm_menu]![cmbMplTag1]
qdf.Parameters("[Forms]![frm_menu]![cmbMplTag2]") = [Forms]![frm_menu]![cmbMplTag2]
qdf.Parameters("[Forms]![frm_menu]![cmbMplTag3]") = [Forms]![frm_menu]![cmbMplTag3]
qdf.Parameters("[Forms]![frm_menu]![cmbMplTag4]") = [Forms]![frm_menu]![cmbMplTag4]
qdf.Parameters("[Forms]![frm_menu]![cmbMplTag5]") = [Forms]![frm_menu]![cmbMplTag5]
Set rst = qdf.OpenRecordset()
rst.MoveFirst
j = -1
i = 0
For i = 0 To rst.Fields.Count - 1
j = j + 1
Select Case j
Case 0
Me.Log_Date.ControlSource = rst.Fields(i).Name
Case 1
Me.Log_Time.ControlSource = rst.Fields(i).Name
Case 2
Me.field1.ControlSource = rst.Fields(i).Name
Case 3
Me.field2.ControlSource = rst.Fields(i).Name
Case 4
Me.Field3.ControlSource = rst.Fields(i).Name
Case 5
Me.Field4.ControlSource = rst.Fields(i).Name
Case 6
Me.Field5.ControlSource = rst.Fields(i).Name
End Select
skip_it:
Next i
rst.Close
Set rst = Nothing
End Sub
Please let me know if I have not provided enough details/information
Check your SQL WHERE clause conditional logic. As is, the logic filters records in either (not both) camps:
Falling in the date range and query's tag equals only form's tag1
Query's tag equals any of form's tag2 - tag5.
Possibly you meant to separate the date range and tags. So wrap parentheses around each condition with an AND operator, even use the IN clause. See below with indentation to illustrate:
...
WHERE (
(
(tbl_logdata.Log_Date) Between [Forms]![frm_menu]![txtFromDate]
And [Forms]![frm_menu]![txtToDate]
)
AND (
(tbl_logdata.tag) IN (
[Forms]![frm_menu]![cmbMplTag1],
[Forms]![frm_menu]![cmbMplTag2],
[Forms]![frm_menu]![cmbMplTag3],
[Forms]![frm_menu]![cmbMplTag4],
[Forms]![frm_menu]![cmbMplTag5]
)
)
)
GROUP BY tbl_logdata.Log_Date, tbl_logdata.Log_Time
You may have to convert to a true date value. And use the Value property:
qdf.Parameters("Forms!frm_menu!txtFromDate").Value = DateValue([Forms]![frm_menu]![txtFromDate])
qdf.Parameters("Forms!frm_menu!txtToDate").Value = DateValue([Forms]![frm_menu]![txtToDate])

creating a loop around my select Case

At present, I have a functioning Select Case that states that if a textbox is blank then it is to be highlighted red, but it only seems to be highlighting one of the textboxes. For instance, if 2 textboxes are left blank, it only highlights the first on it comes across.
Select Case True
Case Me.CustName = ""
Me.CustName.BackColor = &H8080FF
Case Me.RegAddress = ""
Me.RegAddress.BackColor = &H8080FF
Case Me.PostInput = ""
Me.PostInput.BackColor = &H8080FF
Case Me.Landline = ""
Me.Landline.BackColor = &H8080FF
Case Me.Contact = ""
Me.Contact.BackColor = &H8080FF
Case Me.DOBInput = ""
Me.DOBInput.BackColor = &H8080FF
End Select
Being new to VBA, my only thinking is to create a loop round my current code that state (loop until x,y or z is <> "") but I can't seem to figure out how to do this.
Any advice will be greatly appreciated.
Select Case runs the code block following the first matching Case statement only. If you need to check each of your conditions regardless, you should write them as individual If statements instead:
If Me.CustName = "" Then Me.CustName.BackColor = &H8080FF
If Me.RegAddress = "" Then Me.RegAddress.BackColor = &H8080FF
If Me.PostInput = "" Then Me.PostInput.BackColor = &H8080FF
....
You are using Select Case for the wrong purpose. Its purpose is to test a single expression and execute one branch based on the value of that expression.
What you need to do is test each of your text boxes individually, using if statements:
If Me.CustName = "" Then Me.CustName.BackColor = &H8080FF
'etc.

Using Linq in VB.NET to verify result set is NULL

I'm trying to validate wether or not two matching columns exists using Linq/VB.NET
I believe that assuming a null result set is being returned the 'Count' value should also be null, correct?
Below is the code;
Dim crewNumEntered = crewNumInput.Text
Dim crewLeaderNumEntered = crewLeaderNumInput.Text
Dim crewNumUnique As Boolean = False
Using db As New DbClassDataContext
Dim Count = (From a In db.WarrantyPercents Where a.CrewLeaderNum = crewLeaderNumEntered And a.CrewNum = crewNumEntered Select a.WarrantyPercentsId).ToList
If Count Is Nothing Then
crewNumUnique = True
Else
'throw error
End If
End Using
The end result is I only want to perform an action (code not shown) if crewNumUnique == true.
But even when the result set should be null, this code is continuing to fill 'something' with Count.
What can I do to fix this?
EDIT: I just realized the value of count isn't null but instead returning the string 'System.Collections.Generic.List`1[System.Int32]'. Now I have no clue what is going on.
You are calling ToList .. it can never be null.
You should check its length.
If Count.Count = 0 Then
crewNumUnique = True
Else
End If
The query will return a result set even when no matching rows are found.
The below sets crewNumUnique to True if there is exactly 1 result. If instead you want to set crewNumUnique to True when there are no results, use 0 in place of 1.
Dim result = From a In db.WarrantyPercents Where a.CrewLeaderNum = crewLeaderNumEntered And a.CrewNum = crewNumEntered
Dim count As Integer = result.Count
If count = 1 Then
crewNumUnique = True
Else
'throw Error
End If

How can I add two conditional filters to the same IEnumerable?

How can I fuse these 2 If statements to make both my Droplist filters work together to filter the data? I have 2 droplists (transfilter and Soortfilter) and I want to be able to select something out of droplist 1 and select other thing out of droplist 2 and then press filter and have it show the items that have been selected by filtering with both filters.
# this point I have Return View(query.ToList()) what only shows my filter items from Droplist 1
Function Index(transFilter As TransactieType?, soortfilter As Soort?) As ActionResult
Dim query As IEnumerable(Of Pand)
If Not transFilter.HasValue OrElse transFilter.Value = TransactieType.Beiden Then
query = db.Panden
Else
query = db.Panden.Where(Function(p) p.TransactieType = transFilter.Value)
End If
If Not soortfilter.HasValue OrElse soortfilter.Value = Soort.All Then
query = db.Panden
Else
query = db.Panden.Where(Function(p) p.Soort = soortfilter.Value)
End If
Return View(query.ToList())
End Function
I was trying this but that didn't really work
Function Index(transFilter As TransactieType?, soortfilter As Soort?) As ActionResult
Dim query As IEnumerable(Of Pand)
If Not transFilter.HasValue And soortfilter.HasValue OrElse transFilter.Value = TransactieType.Beiden And soortfilter.Value = Soort.All Then
query = db.Panden
Else
query = db.Panden.Where(Function(p) p.TransactieType = transFilter.Value And p.Soort = soortfilter.Value)
End If
Return View(query.ToList())
The problem is that you're setting query = db.Panden in the first part of both If statements. When you're dealing with incrementally building up a LINQ query, always
Start with a base case. In this case it would be Dim query As IEnumerable(Of Pand)
Add each additional filter directly to that base case using query = query.Where.
Function Index(transFilter As TransactieType?, soortfilter As Soort?) As ActionResult
Dim query As IEnumerable(Of Pand) = db.Panden
If transFilter.HasValue AndAlso transFilter.Value <> TransactieType.Beiden Then
query = query.Where(Function(p) p.TransactieType = transFilter.Value)
End If
If soortfilter.HasValue AndAlso soortfilter.Value <> Soort.All Then
query = query.Where(Function(p) p.Soort = soortfilter.Value)
End If
Return View(query.ToList())
End Function

ASP Classic - If test failing

I really do not understand why the if test always fails. I have validated the session variable sCrs_cde (course code) is correct and exists in only one of the multiple records returned by the sql query. (It is part of a foreign key tied to year and semester). I am trying to sert the value for the course title, but it is always writing out as an empty value ('')
Dim Recordset1
Dim Recordset1_cmd
Dim Recordset1_numRows
Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
Recordset1_cmd.ActiveConnection = MM_Jenz_STRING
Recordset1_cmd.CommandText = "SELECT ID_NUM, Crs_Title, YR_CDE, TRM_CDE, CRS_CDE, TRANSACTION_STS, SUBTERM_CDE FROM dbo.STUDENT_CRS_HIST WHERE ID_NUM = ? And Transaction_sts = 'C' "
Recordset1_cmd.Prepared = true
Recordset1_cmd.Parameters.Append Recordset1_cmd.CreateParameter("param1", 5, 1, -1, Recordset1__MMColParam) ' adDouble
Set Recordset1 = Recordset1_cmd.Execute
Recordset1_numRows = 0
%>
<%
Do While not Recordset1.Eof
response.write(Recordset1.Fields.Item("CRS_cde").Value)
IF (Recordset1.Fields.Item("CRS_cde").Value) = (Session("sCrs_cde")) THEN
Session("sCrs_Title") = (Recordset1.Fields.Item("CRS_Title").Value)
Session("sYr_cde") = (Recordset1.Fields.Item("YR_CDE").Value)
Session("sTrm_cde") = (Recordset1.Fields.Item("Trm_Cde").Value)
Session("sSubterm_cde") = (Recordset1.Fields.Item("Subterm_cde").Value)
EXIT Do
ELSE
Recordset1.movenext
END IF
Loop
Thank you everyone. I made a boneheaded mistake every programming 101 class teaches. I did not rtrim the values. I don't know where the extra spaces came from since both values were retrieved from the database (different tables), but after rtrimming both values in the if statement, I finally got it to pass.