In my vb.net winforms project, I have a sub in my form class that I want to exit without doing anything if a certain flag boolean variable (flagDataLoading) is true. But it proceeds to run the contents of the if statement. Why is it doing this?
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Form1
Private flagDataLoading As Boolean = True
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.DataSource = GetTestTable()
flagDataLoading = False
End Sub
Private Function GetTestTable()
Dim dtTest As New DataTable
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Using conn As New SqlConnection(connString)
Using cmd As New SqlCommand("SELECT * FROM dbo.testTable", conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader
dtTest.Load(reader)
End Using
End Using
Return dtTest
End Function
Private Sub DataGridView1_RowEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.RowEnter
If flagDataLoading = False Then ' If the GridView is not still doing its initial load of data from the database table(if the row entry is coming from the database, then it's already saved there.)
Dim reply As DialogResult = MessageBox.Show("Save the current record?", "Question:", MessageBoxButtons.YesNo)
If reply = DialogResult.Yes Then
Dim connectionString As String = "Data Source=(localdb)\ProjectModels;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim insertSql As String = "INSERT INTO dbo.testTable(testColumn) VALUES (@value)"
Using transaction As SqlTransaction = conn.BeginTransaction
Try
For Each row As DataGridViewRow In DataGridView1.Rows
If Not row.IsNewRow Then
Using cmd As New SqlCommand(insertSql, conn, transaction)
cmd.Parameters.AddWithValue("value", row.Cells("column1").Value)
cmd.ExecuteNonQuery()
End Using
End If
Next
Catch ex As Exception
End Try
End Using
End Using
Else
Return
End If
End If
End Sub
End Class
The sub DataGridView1_RowEnter is supposed to prompt the user whether or not to save any entered rows, but it would do this for every existing record from the database during the Form1_Load sub, so I put it in the If statement. flagDataLoading is supposed to indicate whether or not the data grid is still being populated with the data from the database table.
What I have tried:
If I break before the if statement, it shows that the boolean is
true, so not false, meaning the if statement should not run, but it is.