简体   繁体   中英

c# - how to add Collection changed event to windows forms application

I am looking for an event that triggers when the number of rows change, ie the user adds a row or deletes a row in any way. I am trying to use this code, but it's not working.

designer.cs

this.dataGridView1.Rows.CollectionChanged += new System.Windows.Forms.DataGridViewCollectionChangedEventHandler(this.dataGridView1_CollectionChanged);

form1.cs

    private void dataGridView1_CollectionChanged(object sender, DataGridViewRowsAddedEventArgs e)
    {
    }

Does anyone see the problem?

Have you tried looking at the the DataGridView.UserDeletedRow and the DataGridView.UserAddedRow events?

I also was able to get your CollectionChanged Event to fire by setting up the handler like this.

public Form1()
{
    InitializeComponent();
    this.dataGridView1.Rows.CollectionChanged += new CollectionChangeEventHandler(Rows_CollectionChanged);
}

void Rows_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
    Debug.Print(e.Action.ToString()); // to use Debug.Print function add a using System.Diagnostics to your program
    Debug.Print(e.Element.ToString());
    DataGridViewRow row = (DataGridViewRow)e.Element;
}

There are two events available directly on the DataGridView

RowsAdded

RowsRemoved

However, these only fire when the user is adding or removing rows using the DataGridView features. If you want to detect a row added or removed from the underlying DataTable (etc) then you'll need to handle the events your collection exposes.

DataTable s have two events:

TableNewRow

RowDeleted

If these events are not what you are looking for, then you can find the complete DataGridView event documentation here: http://msdn.microsoft.com/en-us/library/x4dwfh7x

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