Using a Case statement with an Int entry from a table
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:
Priv开发者_高级运维ate 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():
精彩评论