Syntax Error in INSERT INTO statement vb.net and an access database - vb.net

The program I'm writing (in vb.net) is supposed to be loading values from text boxes into a database.
However, when I click "Save", at first nothing at all happened. No error, no notification, nothing. So I traced it using breakpoints, and it got to:
daTraining.Update(dsTraining, "Training")
and just stopped.
So I put in a try/catch, and now when I hit save I get
System.Data.OleDB.OledgException (0x80040E14): Syntax error in INSERT INTO statement.
I'm confused on how to troubleshoot this or what the issue might be.
The Code
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
Dim cb As New OleDb.OleDbCommandBuilder(daTraining)
Dim dsNewRow As DataRow
dsNewRow = dsTraining.Tables("Training").NewRow
dsNewRow.Item("ID") = txtTrainingID.Text
dsNewRow.Item("Ranch") = cbRanches.Text
dsNewRow.Item("Location") = txtLocation.Text
dsNewRow.Item("Date") = mtbDate.Text
dsNewRow.Item("StartTime") = mtbStartTime.Text
dsNewRow.Item("FinishTime") = mtbFinishTime.Text
dsNewRow.Item("Crew") = txtCrews.Text
dsNewRow.Item("Supervisor") = txtSupervisor.Text
dsNewRow.Item("Foreperson") = txtForeperson.Text
dsNewRow.Item("Activity") = txtActivity.Text
dsNewRow.Item("Trainer") = txtTrainer.Text
dsNewRow.Item("Topics") = txtTopics.Text
dsTraining.Tables("Training").Rows.Add(dsNewRow)
daTraining.Update(dsTraining, "Training")
MsgBox("Training Recorded")
cb.Dispose()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

This is a common issue when using a data adapter with a wildcard in the query and a command builder. If one or more of your columns names is a reserved word or contains spaces or other special characters then the auto-generated INSERT and UPDATE statements will generate syntax errors.
The preferred solution is to change the offending column name(s) but, if that's not an option, you can set the QuotePrefix and QuoteSuffix properties of your command builder so that it escapes all column names in the generated action commands. The appropriate values will vary depending on your database but for Microsoft databases, use "[" and "]" respectively.

As indicated in comments, the issue was in
dsNewRow.Item("Date") = mtbDate.Text
with Date being a reserved word.

Related

I am using a method with a stored procedure, but it's always returning false

I am using bool method with Visual Studio 2015 and SQL Server 2005.
When I am passing correct details and click loginButton, the code always returns false from the stored procedure.
This is my stored procedure in SQL Server 2005:
ALTER PROCEDURE [dbo].[UserCheckLoginDetails]
(#IsLoginIdCorrect BIT OUTPUT,
#IsPasswordCorrect BIT OUTPUT,
#LoginID NVARCHAR(200),
#Password NVARCHAR(20)
)
AS
BEGIN
SET #IsLoginIdCorrect = 0
SET #IsPasswordCorrect = 0
IF EXISTS (SELECT * FROM UserInfo
WHERE loginid = #LoginID AND password = #Password)
BEGIN
SET #IsLoginIdCorrect = 1
SET #IsPasswordCorrect = 1
END
ELSE
IF EXISTS (SELECT * FROM UserInfo WHERE loginid = #LoginID)
BEGIN
SET #IsLoginIdCorrect = 1
END
END
This is my method returning True or False:
Private Sub GetIsUserLoginCorrect(IsLoginIdCorrect As Boolean, IsPasswordCorrect As Boolean)
Using Conn As New SqlConnection(_SqlCon)
Using cmd As New SqlCommand("UserCheckLoginDetails", Conn)
cmd.CommandType = CommandType.StoredProcedure
Conn.Open()
'OutPut Parameters
cmd.Parameters.Add("#IsLoginIdCorrect", SqlDbType.Bit).Direction = ParameterDirection.Output
cmd.Parameters.Add("#IsPasswordCorrect", SqlDbType.Bit).Direction = ParameterDirection.Output
'InPut Parameters
cmd.Parameters.AddWithValue("#LoginID", LoginIDTextBox.Text)
cmd.Parameters.AddWithValue("#Password", PasswordTextBox.Text)
cmd.ExecuteNonQuery()
' Assign Parameters
IsLoginIdCorrect = Convert.ToBoolean(cmd.Parameters("#IsLoginIdCorrect").Value)
IsPasswordCorrect = Convert.ToBoolean(cmd.Parameters("#IsPasswordCorrect").Value)
End Using
End Using
End Sub
This is the Login button click event handler, even when I provide the correct values, it still always returns false:
Private Sub LoginButton_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
Try
Dim IsLoginIdCorrect, IsPasswordCorrect As Boolean
GetIsUserLoginCorrect(IsLoginIdCorrect, IsPasswordCorrect)
If IsLoginIdCorrect And IsPasswordCorrect = True Then
Me.Hide()
' User Information
DeshBoard.MainUserIdLabel.Text = Me.MainUserIdLabel.Text
DeshBoard.UserNameLabel.Text = Me.UserNameLabel.Text
DeshBoard.UserLoginIdLabel.Text = Me.UserLoginIdLabel.Text
DeshBoard.UserLevelLabel.Text = Me.UserLevelLabel.Text
'Organanization Information
DeshBoard.MainOrgIDLabel.Text = Me.MainOrgIDLabel.Text
DeshBoard.OrgNameLabel.Text = Me.OrgNameLabel.Text
DeshBoard.OrgTelLabel.Text = Me.OrgTelLabel.Text
DeshBoard.OrgEmailLabel.Text = Me.OrgEmailLabel.Text
DeshBoard.OrgAddressLabel.Text = Me.OrgAddressLabel.Text
DeshBoard.Show()
Else
If IsLoginIdCorrect = False Then
MessageBox.Show("Login ID is not correct...!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
LoginIDTextBox.Clear()
PasswordTextBox.Clear()
LoginIDTextBox.Focus()
Else
MessageBox.Show("Password ID is not correct...!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
PasswordTextBox.Clear()
PasswordTextBox.Focus()
End If
End If
Catch ex As ApplicationException
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Thank you very much.
You need to add ByRef to both arguments in Sub GetIsUserLoginCorrect().
To demonstrate, try the following with and without ByRef.
Private Sub ChangeBoolean(ByRef TorF As Boolean)
TorF = True
End Sub
Private Sub OPCode2()
Dim TorF As Boolean
ChangeBoolean(TorF)
Debug.Print(TorF.ToString) ' Result False without ByRef in ChangeBoolean
'When ByRef is added result is True
End Sub
First off, a method can refer to either a sub or a function. A sub is a method that performs an action. A function is a method that calculates or retrieves one or more values.
A sub should not be called Getxxx, because its primary purpose should not be returning a value.
A function should be used to return values. Since you are trying to retrieve multiple values, if you were using 2017 I would suggest returning a named tuple with your two values, since you aren’t I would create an object that has the values and return that.
On a totally different note, you really can’t tell the difference between right user wrong password and wrong user right password and wrong user wrong password - so you shouldn’t tell someone you can. You just say login unsuccessful login, or invalid username/password combination.
There's a lot wrong with your code.
Firstly, why are you using so much of SQL code ? Correct me if i am wrong : You are trying to build a log in system. So much of SQL code or even the stored procedure is worthless here. You can simply write the SQL statements in your code by using the SqlCommand class. Even though you are using the ALTER PROCEDURE statement, i can surely say that things can be simplified here.
You are also using the Me keyword. It's not C# where the use of this(same as Me in VB.Net) becomes compulsory. I assume it's a Windows Forms Application and if that's so, then using Me keyword to access it's child elements wouldn't result in any different if it's not used at all.
The next worth mentioning issues is your Name Conventions. Most or should i say all of your variables have the same name. For example : IsLoginIdCorrect - used both as a parameter of a method and also a variable inside a method.
The next issues is in these two lies :
Dim IsLoginIdCorrect, IsPasswordCorrect As Boolean
GetIsUserLoginCorrect(IsLoginIdCorrect, IsPasswordCorrect)
You are passing the boolean variables before they have been assigned any value. You are lucky it's not C# or this wouldn't even compile. Passing the boolean variables without assigning any value will, by default, set their values to False. So, literally, you are always passing the same value in which case, the outcome will always be the same.
The next issue is in your If statement inside your LoginButton_Click method aka LoginButton's click event handler's method :
If IsLoginIdCorrect And IsPasswordCorrect = True Then
The if statements, if described in simple words, means : If IsLoginIdCorrect and IsPasswordCorrect are true, then proceed.... So, in this case, IsPasswordCorrect = True doesn't affect much. However, this is not the best practice too. You should better follow the following coding rule while using If statements:
If (IsLoginIdCorrect = True AndAlso IsPasswordCorrect = True) Then
AndAlso operators evaluates each side just like the And operator. The difference is that it would return False if the left side(IsLoginIdCorrect, in this case) returns False.
The next issues is the usage of ApplicationException. I don't understand why, in this era, you are using that class! This class is usually used to derive from and create exceptions. You can simply use Exception instead of ApplicationException.
Your Try-Catch block seems not useful as well. All of your codes inside the LoginButton_Click are in If conditions and they perform very basic operation. It is unlikely to ever throw any exception at all.
Your logics, for most part, are illogical(sorry to put it this way). In your GetIsUserLoginCorrect method, you are setting IsLoginIdCorrect and IsPasswordCorrect to either true or false but it wouldn't matter because they are parameters of the method itself. So even if you set their values, they will be reset when you call the method again. The reason why ByRef (according to Mary's answer) works is because ByRef, in short, means that you are pointing to original variable that you passed(not it's copy).
And finally, the solution you are looking for....
Even though i see you have marked Mary's answer as the answer, i would like to help you out a bit as-well.
Firstly, get rid of the stored procedure if possible and also if you are not using it anywhere else. I see you are using the If Exist condition inside your SQL queries. This is actually a nice move because according to performance reports, checking if data exists in a database/table using IF EXISTS yields the fastest output. So bravo for that one. But if you follow my advice and want to ditch the stored procedure, then you need to get rid of the IF EXISTS statement as well. Rather, you can simply use the SELECT statement itself, use the ExecuteScalar method of the SqlCommand class, convert it's value to Integer and check if the value of the Integer is 1 or not.
Example :
Dim cmd = New SqlCommand("SELECT COUNT(*) FROM UserInfo
WHERE loginid = #LoginID AND password = #Password")
Dim Exists = Convert.ToInt32(cmd.ExecuteScalar)
If Exists = 1 Then
''Code if data exists
End if
Note that i have used Convert.ToInt32 here. This will prevent null-reference exception as when ExecuteScalar returns Null, it will be converted to 0 integer value.
Also, why are you using GetIsUserLoginCorrect as method ? You can simply use it as a function and return required values. As you are returning multiple values, you can easily use the Tuple type as your function's type:
Private Function GetIsUserLoginCorrect(IsLoginIdCorrect As Boolean, IsPasswordCorrect As Boolean) As Tuple(of Boolean, Boolean)
....
....
return Tuple.Create(IsLoginIdCorrect, IsPasswordCorrect)
End Sub
Usage
Dim IsLoginCorrect = GetIsUserLoginCorrect(first_boolean_variable,second_boolean_variable).Item1
Dim IsPasswordCorrect = GetIsUserLoginCorrect(first_boolean_variable,second_boolean_variable).Item2
One last thing. As you are showing DeshBoard form after hiding the main form, make sure to call MainForm.Close on the Dashboard form's Closing/Closed event. This will ensure the application's exit(unless you have other plans for the main form, of course).
Hope this answer helps you.

Updating row in database using vb.net

I am trying to update and save a row of a database table. I have used a version of this code to just populate a GridView and it works, so I am assuming it has something to do with my SQL statment; I do not get an error, the table just does not update. On the page load event I have the textboxes being populated by the information of the row, and I have a global variable, named 'temp', that will save the title of the row so I can use it in the button's click event. The error I am getting states that I have not given a value for one of my required parameters. My Locals tab on the debugger shows that every variable has a value, though the one I try to update is not the new data but still the old data.
I have looked at several examples and I cannot find the problem though. Thank you for any assistance.
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
Dim strTitle As String = txtTitle.Text
Dim strConsole As String = txtConsole.Text
Dim strYear As String= txtYear.Text
Dim strPurchase As String = calDate.SelectedDate.ToString
Using con As OleDbConnection = New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "DATA SOURCE=" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "App_Data", "db1.accdb"))
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.CommandText = Convert.ToString("UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Purchase = #Purchase WHERE Title=" & temp)
cmd.Connection = con
cmd.Parameters.AddWithValue("#Title", strTitle)
cmd.Parameters.AddWithValue("#Console", strConsole)
cmd.Parameters.AddWithValue("#Year_Released", strYear)
cmd.Parameters.AddWithValue("#Purchase", strPurchase)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Server.Transfer("Form.aspx", True)
End Sub
I have also tried the have my where statement as: WHERE Title='" & temp & "'") Though this does not work either.
This is the details of the Error message
I changed you commandText as seen below and created a blank database with a table named just like yours and the update worked
cmd.CommandText = "UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Purchase = #Purchase WHERE Title='" & temp & "'"
I set my variable for Title = Super Mario Bros and then the temp variable to Wario World. I had a record in my database with the title of Wario World, and running the update changed the title to Super Mario Bros.
Check if you temp variable is different from your #title variable. Also check that you have the record int the table for your temp variable title
Thank you all for your assistance, This is such a wonderful community.
The problem, I found out, does not even have to do with the button's click event, it had to do with the page load event. Since on page load the row's information is loaded and populated into the textboxes, when the button is clicked to update the fields, the page load event triggers again and reloads the old information into fields, essentially saving the old information instead of the new. My fix was to create an If Not IsPostBack Then statement that encapsulates my on page load code. Therefore the code does not get saved when the button is pressed. Another this, I did not need the temp variable, using WHERE Title='" + strTitle + "'" worked. Hopefully this helps other people stuck on a similar problem!
Using dates in a where clause is always ify as they are floating point numbers and may not match equally. I'd try and round them or convert them to strings before comparison, e.g. something along these lines:
UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Format(Purchase, ""m/d/yyyy"") = Format(#Purchase, ""m/d/yyyy"") WHERE Title = #Title

Moving Data From Databound Listbox To Unbound Listbox And Back VB.NET

So I have been browsing about and there are a lot of explanations on how to move data from listbox to listbox.
I have a listbox bound to a source from my SQL server and another unbound. My aim is to move the data from the first (LBsearch) to the second (LBselect) and back. I have seen people say use
LBselect.Items.Add(LBsearch.SelectedItem) however it doesn't return data and instead shows System.Data.DataRowView. I've tried many different suffixes and all show this apart from LBsearch.text. Then to remove the data from the first one I've been removing the databindingsource (PersonBindingSource) with
PersonBindingSource.Remove(LBsearch.SelectedItem) but my issue is adding the data back again.
PersonBindingSource.Add(LBselect.SelectedItem) gives an error:
System.InvalidOperationException: Objects added to a BindingSource's list must all be of the same type.
at System.Windows.Forms.BindingSource.Add(Object value)
at Project_Program.Participants.btnremoveselect_Click(Object sender, EventArgs e) in E:\Documents\Visual Studio\Project Program\Project Program\Participants.vb:line 39
PersonBindingSource.Add(PersonBindingSource.Item(LBsearch.SelectedIndex))
gives an error:
System.ArgumentException: Cannot add external objects to this list.
at System.Data.DataView.System.Collections.IList.Add(Object value)
at System.Windows.Forms.BindingSource.Add(Object value)
at Project_Program.Participants.btnremoveselect_Click(Object sender, EventArgs e) in E:\Documents\Visual Studio\Project Program\Project Program\Participants.vb:line 38
Any help would be appreciated. Thanks
Private Sub btnaddselect_Click(sender As Object, e As EventArgs) Handles btnaddselect.Click
If LBsearch.Items.Count > 0 Then
MsgBox(LBsearch.Text)
' PersonBindingSource.Remove(PersonBindingSource.Item(LBsearch.SelectedIndex))
LBselect.Items.Add(LBsearch.Text)
PersonBindingSource.Remove(LBsearch.SelectedItem)
' filter()
End If
End Sub
Private Sub btnremoveselect_Click(sender As Object, e As EventArgs) Handles btnremoveselect.Click
If LBselect.Items.Count > 0 Then
Try
'PersonBindingSource.Add(PersonBindingSource.Item(LBsearch.SelectedIndex))
PersonBindingSource.Add(LBselect.SelectedItem)
MsgBox(LBselect.SelectedItem.ToString())
LBselect.Items.Remove(LBselect.SelectedItem)
Catch ex As Exception
TextBox1.Text = (ex.ToString)
End Try
'filter()
End If
End Sub
A major problem with moving rows is that since they are DataRows, they will not display well in the unbound control. If you pull out something useful like a name, you will have to recreate the DataRow to return it to the original/bound/source control.
This is a problem because, now it is a new row, so a DataAdpter might add it to the database again! One way to avoid that is to clone the table. Also, if/when you move them back, they will appear at the bottom of the list and not in their original position.
There is a better way than duplicating the table data and moving anything anywhere.
Since the act of being selected can be represented with a simple Boolean, it can be coded so that the Selected ones show in one control, the unSelected ones in the other. For this, a new Selected column is needed. If possible, add one using your SQL:
' MS Access syntax
Dim SQL = "SELECT a, b, c,..., False As Selected FROM tblFoo"
This will create the new column in your datatable with all the values initialized to False. You can also add the column manually.
' form level vars
Private dvSource As DataView
Private dvDest As DataView
...
' set up:
' *** Add a column manually if you cant use SQL
dtSample.Columns.Add("Selected", GetType(Boolean))
' we need to loop and set the initial value for an added column
For Each r As DataRow In dtSample.Rows
r("Selected") = False
Next
' *** end of code for adding col manually
' when the column is added from SQL, you will need:
dtSample.Columns("Selected").ReadOnly = False
' create Source DV as Selected = False
dvSource = New DataView(dtSample,"Selected=False", "",
DataViewRowState.CurrentRows)
' create Dest DV as Selected = True
dvDest = New DataView(dtSample, "Selected=True", "",
DataViewRowState.CurrentRows)
' assign DS
lbSource.DataSource = dvSource
lbSource.DisplayMember = "Name"
lbSource.ValueMember = "Id"
lbDest.DataSource = dvDest
lbDest.DisplayMember = "Name"
lbDest.ValueMember = "Id"
Then in the click events:
' select
CType(lbSource.SelectedItem, DataRowView).Row("Selected") = True
' deselect:
CType(lbSource.SelectedItem, DataRowView).Row("Selected") = False
The two DataView objects will filter on Selected inversely. When you change the state of a row, it is instantly removed from one and appears in the other without actually being added/removed from any table (or collection or control). If you move it back to the Source it will appear in the same position as before.
In this case, the RowState of any item moved will be Modified, which of course it is (unlike the move-to-table approach where they would be new rows (Added) which they are not).
It is hard to illustrate without 5 or 6 images, but the idea:
It is actually a pretty simple method and more economical than one invovling actually moving rows. Using DataViews the rows/items look like they move to another table or control, but they do not, nor do they need to.

Check DGV row for missing value with an sql bound back end

I am currently working in vb.net windows express 2013 with an sql back end. I am trying to create an if statement that will look at a specific cell and make a decision based on if the cell has nothing in it or not. I think the return for an sql statement is null but im not 100% sure. I have tried lots of codes I dug up on the internet but none of them have worked for me so far. Here is the line:
Dim Row_Index As Integer = DGVStart.CurrentCell.RowIndex
If DGVStart.Rows(Row_Index).Cells(1).Value Is Nothing Then
This code does work, as in the windows express is telling me the line is fine, however, it seems that I am always getting the return of nothing, even if something is in the cell.I think this problem has something to do with the way i am pulling the value. I have a datagridview checkbox column which i manually added in the design form and if i change it to cells(0), which is my manually inserted column, it picks it up every time. I need to know how to tell my program to differentiate between is null and is not null.
UPDATE: I am now running into new issues after changing to searching for dbnull. here is my code.
Private Sub DGVStart_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVStart.CellContentClick
'dim start time
Dim start As String = TxtStart.Text
'fail safe so headers cant be clicked
If e.RowIndex = -1 Then
Exit Sub
End If
'dim row index and check, check is for the parts shear columns
Dim Row_Index As Integer = DGVStart.CurrentCell.RowIndex
'Dim check As String = DGVStart.Rows(Row_Index).Cells(2).Value
'if checkbox is clicked
If e.ColumnIndex = 0 Then
'---------------------------------------------Normal parts---------------------------------------------------------------
'If DGVStart.Rows(Row_Index).Cells(1).Value Then
If IsDBNull(DGVStart.Rows(Row_Index).Cells(3).Value) = True Then
Dim Shear As Date = DGVStart.Rows(Row_Index).Cells(5).Value
Dim Machine As Int16 = DGVStart.Rows(Row_Index).Cells(4).Value
Dim ShearNumber As String = DGVStart.Rows(Row_Index).Cells(1).Value
Dim Parts As String = DGVStart.Rows(Row_Index).Cells(3).Value
'Pull Values for sql statement and other operations
Try
'set up for checkbox event to trigger
If e.ColumnIndex = 0 Then
'safety messagebox
Dim result As Integer = MsgBox("Are you sure Shear Number " & ShearNumber & " is being started?", MessageBoxButtons.YesNo)
'if messagebox is no
If result = DialogResult.No Then
Exit Sub
'if messagebox is yes
ElseIf result = DialogResult.Yes Then
'sql update
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("UPDATE table1 SET " & start & " = getdate() Where col = value AND col = value", conn1)
With comm1.Parameters
.AddWithValue("#Shear", Shear)
.AddWithValue("#Machine", Machine)
End With
comm1.ExecuteNonQuery()
End Using
conn1.Close()
End Using
End If
End If
Catch ex As Exception
MsgBox(ex.ToString)
MsgBox("Error checking off start date for this machine, please contact the manufacturing enginnering department.")
End Try
Call refresh()
Call refresh2()
'--------------------------------------------------------Parts special--------------------------------------------------
Else
MsgBox("Parts")
End If
End If
End Sub
***Please note my sql statements have been modified to protect the company I am working for but I am sure the sql code works.
NEW PROBLEM: I am receiving a null error message because if i uncomment this line:
If DGVStart.Rows(Row_Index).Cells(1).Value Then
Then I am trying to see if a cell is null but that causes an error. I am trying to use my if statement to either run the normal parts, or special parts of my code.
Thanks,

Coderush plugin not generating correct try catch end try block

We've created a little plugin to add a block of xml comment and create a try-catch to a function. (we simply add this to each and every function we write)
But with the latest devexpress update I'm having a problem with the following code.
Private Sub cpAddComment_Apply(ByVal sender As System.Object, ByVal ea As DevExpress.CodeRush.Core.ApplyContentEventArgs) Handles cpAddXMLCommentAndTryCatch.Apply
' create elementbuilder and add current code to it
Dim objMethod As New Method
objMethod = objOldMethod.Clone()
objElementBuilder.AddStatement(Nothing, objMethod)
' add try
Dim objTry As DevExpress.CodeRush.StructuralParser.Try = objElementBuilder.AddTry(objMethod)
Dim objCatch As DevExpress.CodeRush.StructuralParser.Catch = objElementBuilder.AddCatch(objMethod, "Exception", "ex")
' add exception
Dim strErrorString As String = """Error in " + objMethod.Location + """, ex"
Dim objThrow As New DevExpress.CodeRush.StructuralParser.Throw
Dim objException As New DevExpress.CodeRush.StructuralParser.TypeReferenceExpression("Exception")
Dim objExceptionString As New DevExpress.CodeRush.StructuralParser.PrimitiveExpression(strErrorString)
Dim objNewException As New DevExpress.CodeRush.StructuralParser.ObjectCreationExpression(objException)
objNewException.AddArgument(objExceptionString)
objThrow.Expression = objNewException
'objThrow.AddFooter(" ") 'This isnt working either
objElementBuilder.AddThrow(objCatch, objThrow)
' substitute code
Dim newCode As String = objElementBuilder.GenerateCode()
ea.TextDocument.Replace(objOldMethod.Range, newCode, "Update Method", True)
end sub
Instead of generating a correct Try-catch block it generates the following incorrect code:
Try
Catch ex As Exception
Throw New Exception("Error in test", ex)End Try
Strangely enough the following code seems to work(its about the same code but then for event handlers to show a messagebox instead of an exception)
If not CodeRush.Language.ActiveExtension.DotNetLanguageType = DotNetLanguageType.CSharp Then
Dim objExceptionString As New DevExpress.CodeRush.StructuralParser.PrimitiveExpression("Messagebox.Show(" + strErrorString + ")" + vbCrLf)
objElementBuilder.AddStatement(objCatch, objExceptionString)
Else
This problem exists in Vb.Net but in C# the brackets are correctly placed.
I have reproduced your issue and registered it in DevExpress Support Center. You are welcome to track its status here. Once it is fixed, you can request a build containing the fix from the Support Team at support # devexpress.com. For now, as a work-around, you can replace this line of code:
objThrow.Expression = objNewException
into this:
objThrow.Expression = New SnippetExpression(CodeRush.Language.GenerateExpressionCode(objNewException) + vbCrLf)
This will generate the try/catch block correctly in Visual Basic.