Click here to Skip to main content
15,940,218 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my 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)
                Dim reader As SqlDataReader = cmd.ExecuteReader
            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)

                    Dim insertSql As String = "INSERT INTO dbo.testTable(testColumn) VALUES (@value)"
                    Using transaction As SqlTransaction = conn.BeginTransaction
                            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)
                                    End Using
                                End If
                        Catch ex As Exception

                        End Try
                    End Using
                End Using
            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.
Updated 22-Feb-23 6:51am

I realized what is going on here. Once all the data from the database table has been loaded into DataGridView1, flagDataLoading is set to false, and after that, a blank line is added to the dataGridView (for entering new data), which sets the DataGridView1_RowEnter sub into motion, which, because the flag has already been switched, runs the contents of the If statement. This is not really a solution, more an explanation. I'm going to try approaching my goal here from a bound grid approach, instead, since I don't have any idea of how to approach this.
Share this answer
You assign value to the flag after you set the DataSource - but the RowEnter event will not be actioned until the Load event method is finished. By that time, the flag has been reset already.

Try setting the flag to false in the Shown event instead of Load. That may delay it enough for your code to function - but if it doesn't, you'll have to add a timer to "wait" for the function to be completed.
Share this answer
Aaron Gerber 20-Feb-23 13:22pm    
Hmm...actually, what I'm doing is initializing the flag value as true and switching it to false once the data for the datagridview has loaded. As I said, I put a break before the if statement to check what the value of the flag was, and it was true, indicating that the Form1_Load had not yet finished loading the data into the grid. It's simply either misreading the value of the flag or ignoring the fact that it's an if statement.
Ralf Meier 20-Feb-23 15:30pm    
at 1st :
I would code "if not flagDataLoading then ..." instead of "if flagDataLoading = false then ..."

But ...
when do you set flagDataLoading to True ?
I suppose that there is the problem ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900