我用 DataGridView 创建了新的窗体应用程序。这是它唯一的形式。DataGridView1_UserDeletingRow 方法中的MessageBox 被调用了3 次。我真的需要明白为什么会这样。明显的问题是DataSource,因为手动添加行到dataGridView,方法没有不必要地调用3次。
我还发现如果我把这行代码
dataGridView1.RowsRemoved += new DataGridViewRowsRemovedEventHandler(DataGridView1_UserDeletingRow);
后
dataGridView1.DataSource = dt;
一切正常,并且没有调用 DataGridView1_UserDeletingRow 方法。
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;
}
}
}
谁能解释一下到底发生了什么?