简体   繁体   中英

DataGridView's UserDeletingRow method is called 3 times by itself

I created new windows form application with DataGridView. This is the only form it has. The MessageBox in DataGridView1_UserDeletingRow method is called 3 times. I rly need to understand why is that. The obvious problem is DataSource, because adding rows manually to dataGridView, method is not unnecessarily called 3 times.

I also found out that if I put this line of code

dataGridView1.RowsRemoved += new DataGridViewRowsRemovedEventHandler(DataGridView1_UserDeletingRow);

after

dataGridView1.DataSource = dt;

everything works fine and method DataGridView1_UserDeletingRow is not called.

using System;
using System.Data;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            MessageBox.Show(sender.ToString());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.RowsRemoved += new DataGridViewRowsRemovedEventHandler(DataGridView1_UserDeletingRow);

            var dt = new DataTable("myTableName");
            dt.Columns.Add("myColumnName");
            dt.Rows.Add(new object[] { 123 });

            dataGridView1.DataSource = dt;
        }
    }
}

Can anyone please explain what exactly is happening?

Hey I just had the same problem and this is how I fixed it:

protected override void OnUserDeletedRow(DataGridViewRowEventArgs e)
{
    base.OnUserDeletedRow(e);

    //You're code here
}

I used override on the DataGridView function OnUserDeletedRow, called the base function and added the code I wanted to trigger.

This function only triggered once and solved my problem, you can also override other function like this as an alternative to listening to an event.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM