How to set AllowUserToAddRows with ToolStripButton1.Click without adding rows in DataGridView

Mansour_Dalir 1,936 Reputation points
2024-07-29T08:08:15.6333333+00:00

20240729_110424 hi

What is the best way to toggle the AllowUserToAddRows variable between true and false based on a ToolStripButton1.Click event, without adding rows to the DataGridView? I have implemented the button click event, but it currently adds a row to the DataGridView, which is not the desired behavior. One solution I found was to lose focus on the DataGridView, but I am hoping for a cleaner way to accomplish this.

Public Class Form2
    Dim myTable As New DataTable()
    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
        myTable.Columns.Add("Name")
        DataGridView1.DataSource = myTable
        DataGridView1.AllowUserToAddRows = False
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'No Problem
        DataGridView1.AllowUserToAddRows = Not DataGridView1.AllowUserToAddRows
    End Sub
    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        'But This Event Problem?
        DataGridView1.AllowUserToAddRows = Not DataGridView1.AllowUserToAddRows
    End Sub
End Class
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,903 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,738 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 32,376 Reputation points Microsoft Vendor
    2024-07-29T09:19:13.2466667+00:00

    Hi @Mansour_Dalir ,

    You can move the focus to other control before setting the DataGridView's AllowUserToAddRows property.

    
        Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
            Button1.Focus()
            DataGridView1.AllowUserToAddRows = Not DataGridView1.AllowUserToAddRows
        End Sub
    
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.