Please see the code below:
Dim strHideReason As String = strHideReason & " " & objDBDR.GetName(intHideCheck) & " is " & objDBDR(intHideCheck)
objDBDR(intHideCheck) is null. objDBDR is a datareader.
The code above compiles, however I am trying to set option strict to on, so I now have to do this:
Dim strHideReason As String = strHideReason & " " & objDBDR.GetName(intHideCheck) & " is " & cstr(objDBDR(intHideCheck))
It now throws an exception. I can refactor the code to resolve this, however I am confused why the first compiles. Does the compiler ignore objects that are null in string concatenations when option strict is off?
When you have OPTION STRICT OFF:
On runtime your object objDBDR(intHideCheck) will be automatically converted(if it possible) to type string.
From MSDN
For strings in Visual Basic, the empty string equals Nothing
objDBDR(intHideCheck) return Nothing which will be converted to string as empty string.
When you have OPTION STRICT ON:
This option restrict implicit conversions, and you must convert objects to string by your self.
For function Cstr if parameter is null, then runtime error will be throw
This answer will explain why runtime error will be thrown:
https://stackoverflow.com/a/979911/1565525
Related
so I'm trying to run this SQL script within a function I call and it's giving me a "Compile Error: Object Required" when I try to run it!
Code calling the function
Private Sub cmdLogin_Click()
Call Load_Username(Username)
End Sub
Function being called
Private Sub Load_Username(Text As String)
Dim SQL As String
Set SQL = "UPDATE tbleUsername " & _
"SET Username = '" & Text & "' " & _
"WHERE ID = 1"
DoCmd.RunSQL SQL
End Sub
Dim SQL As String
Set SQL = "string literal"
You can't use Set to assign a string literal. Use Set to assign object references. That assignment is illegal, because an object is required. Hence, Object required.
Two possible fixes:
Remove the Set keyword and use the wonderful implicit value assignment syntax.
Replace the Set keyword with the obsolete Let keyword for a long-deprecated explicit value assignment syntax. Only suggesting because I'm seeing you use the long-deprecated Call keyword too.
I think that you should define variable Username before call function LoadUsername(UserName)
I am using START-PROCESS to call MSTEST with multiple arguments that define the container and test settings, however I think it's choking on the way I'm concatenating this. Should I use some other method of constructing this string before putting it into START-PROCESS?
Dim rwSettings As String = "\\PerfvsCtlr2\LoadtestSettings\PerfVSCtlr2forRemote.testsettings"
Dim rwContainer As String = "\\PerfvsCtlr2\LoadTest\LoadTestDefs\Heifer_Interactive_Peak_Workload.loadtest"
Dim rwResults As String = Workload.txtRwResults.Text
System.Diagnostics.Process.Start(Environment.GetEnvironmentVariable("VS110COMNTOOLS") & "..\Ide\MSTEST.EXE", "/Testsettings:""" & rwSettings & "" & " /Testcontainer:""" & rwContainer & "" & " /Resultsfile:""" & rwResults & "")
The problem is unknown currently, because process.start opens and closes the window far too quickly for me to catch any sort of error message. So my question is two-fold:
Does the above concatenation look correct? Is there a way I can get more information on either the final execution string Process.Start is putting together or the error message it's returning?
You can use Path.Combine to build paths and String.Format to build the arguments for Process.Start:
Dim rwSettings As String = "\\PerfvsCtlr2\LoadtestSettings\PerfVSCtlr2forRemote.testsettings"
Dim rwContainer As String = "\\PerfvsCtlr2\LoadTest\LoadTestDefs\Heifer_Interactive_Peak_Workload.loadtest"
Dim rwResults As String = "Workload.txtRwResults.Text"
Dim fileName = System.IO.Path.Combine(Environment.GetEnvironmentVariable("VS110COMNTOOLS"), "Ide\MSTEST.EXE")
Dim args = String.Format("/Testsettings:{0} /Testcontainer:{1} /Resultsfile:{2}", rwSettings, rwContainer, rwResults)
System.Diagnostics.Process.Start(fileName, args)
However, i must admit thar i'm not sure if this yields the desired result. It might give you an idea anyway.
I suspect that your problem is that you are not closing your quotation marks, for instance:
" /Testcontainer:""" & rwContainer & ""
Should be:
" /Testcontainer:""" & rwContainer & """"
Notice that the double-quotation mark at the end needs to be a quadruple quotation mark. Simply saying "" means an empty string.
Should you use something else? Probably. It would be more readable and efficient if you used StringBuilder or String.Format, but even so, you'll still have to fix the closing quotes issue.
When i using this const statement,my coding work fine.
Const strFullName As String = "C:\Sample\Haha.txt"
After i change the Search.text (Textbox Name),it keep on come out the error.
Const strFullName As String = "C:\Sample\" & Search.Text & ".txt"
Compile error:
Constant expression required
Then i try create a textbox1.text = Searchbox.Text. The textbox1 shows C:\Sample\Haha.txt
Please Help,Thanks~
Search.Text is not a constant value - it's a run-time property and its value is not known until run-time so it cannot be assigned to a constant. You can just define your strFullName as a variable instead of a constant:
Dim strFullName As String
...
' Set strFullName at run-time
strFullName = "C:\Sample\" & Search.Text & ".txt"
If Search is a textbox, you may also want to check if it has valid input to make sure that you're not trying to form an invalid file name; for example, you can use Len(Search.Text) to determine the length of the text in the textbox.
I have encountered something I would like explained. I have a function InitializeValues() that sets up a combobox, and sets the datasource to a datatable. The datatable is retrievedfrom an instance of the class DGVMain_Functions using the public method GetFileSourceData which takes no parameters.
The issue is that a call to GetFileSourceData(MyConnectionString) will actually compile and run. A run time error occurs when the datatable is returned and attempted to set to the datasource of the cbo. The normal call GetFileSourceData() works properly.
I had asked another developer about this, and he thought I had some stale reference, so I cleaned the project, then deleted everything in my debug folder, and rebuilt, but it still had the same behavior.
My question is this, Why does the compiler accept this and not throw a syntax error, and furthermore why does it even get to the point where you can actually step into this function that should not exist, and have it fail on return?
EDIT: Putting Option Strict On, does make the compiler catch this. "Option Strict On disallows implicit conversions from 'String' to 'Integer'. But that is still not the error I want to see. I would like to know why it does not display something along the lines of "No such overload/definition of that function exists".
The error is this:
An error occurred creating the form. See Exception.InnerException for details. The error is: ERROR: ERROR: Conversion from string "user id=XXXX;data source=XXXXX" to type 'Integer' is not valid.Microsoft.VisualBasicFileProcessor.
"InnerException = {"Input string was not in a correct format."}"
Private Sub InitializeValues()
cboFileSource.DisplayMember = "filesource"
cboFileSource.ValueMember = "filesource"
'first call works fine since it matches
cboFileSource.DataSource = DgvMain_functs.GetFileSourceData()
'below is the call that gets through the complier and actually runs, fails on return
cboFileSource.DataSource = DgvMain_functs.GetFileSourceData(MyConnectionString)
End Sub
Public Function GetFileSourceData() As DataTable
Try
Dim dt As DataTable
Dim strSQL As String = "select distinct filesource from FileUpload_FolderPath"
dt = SqlHelper.ExecuteDataset(MyConnectionString, CommandType.Text, strSQL).Tables(0)
Return dt
Catch ex As Exception
Throw New Exception("Error in DGVMain_Functions: " & ex.Message & ex.Source)
End Try
End Function
As you've hinted in your comment, surely Option Explicit On would solve this issue.
I am using this code and getting error of type mismatch, runtime error '13'
Error is in line which is marked below, And specifically error is due to where condition (prereq.paid=" + rs1!paid + " ") in query...
rs1.Open "select name,nposts,postad.paid as paid from ad,post,postad where ad.adid = " +
cmbAdno.Text +
" and ad.adid=postad.adid and postad.pid=post.pid ", con, adOpenDynamic,
adLockOptimistic
While Not rs1.EOF
cmbTitle.AddItem (rs1!Name)
rs1.MoveNext
Wend
rs1.MoveFirst
cmbTitle.Text = rs1!Name
txtNposts.Text = rs1!nposts
If IsNumeric(rs1!paid) Then
MsgBox (rs1!paid + 1)
End If
**rs2.Open "select title from postad,prereq where postad.paid = prereq.paid and prereq.paid=" +
rs1!paid + " ", con, adOpenDynamic, adLockOptimistic**
While Not rs2.EOF
lstPrereq.AddItem (rs2!Title)
rs2.MoveNext
Wend
rs2.Close
rs1.Close
Whew, that code needs some work!
The plus operators are the culprit here though. You can easily verify this with a small test case.
Dim ADO_Field_Value As Variant
Dim S As String
ADO_Field_Value = True
On Error Resume Next
S = "text" + ADO_Field_Value + ""
If Err Then MsgBox "Plus failed, err " & CStr(Err)
Err.Clear
S = "text" & ADO_Field_Value & ""
If Err Then MsgBox "Amp failed, err " & CStr(Err)
If you run this the "+" yields an error 13 while the "&" works as expected.
Use the ampersand for concatenation. The plus only sorta, kinda works for backward compatibility with ancient times. Using it requires the compiler to guess at your intent in order to resolve the soft overloading of the operator.
Your "Null hack" concatenting an empty String to the .Value isn't particularly clever. If rs1 has a Null there you end up with a SQL syntax error, unless you use "+" which gets you an error 94.
ADO Field values are safer to access by explicitly using .Value instead of letting the compiler guess you want the default property of the Field. While/Wend is obsolete, and what's with those extraneous parentheses?
You are asking the compiler to do things it probably shouldn't in this code.
is rs1!paid a boolean in the database? if so, maybe there is an issue with the concat to make the query string.
In the old days, when i used VB6 i never accessed fields like that. I used something like rstRecordSet.Fields(0) or rstRecordSet.Fields("field1") but that should not be the problem if the field exists.
Create a string before and pass it the concatenation of the query and verify that it gets filled.
Also, you have "...postad.paid as paid...", why? you dont need to rename the field there...