I’m still learning how to use Events in C# so I’ve come up with what should be a fairly simple practice example. I have an object that reads from a database into a List. When an item in the database gets deleted an event is triggered. How do I have a DBWrapper object listen for an event triggered by another class?
public class DBWrapper
{
private List<DBStruct> _List;
public List<DBStruct> GetList
{
get
{
return _List;
}
}
void OnDeleted(object sender, EventArgs e)
{
//Re-read the list from db. I could probably do
//something with Lazy<T> loading to eliminate the event stuff
//but that's not the point.
_List = (from d in db select d).ToList();
}
}
I then have another class with a Delete() method that triggers an event:
public class DeleteDB
{
public void Delete(int index)
{
//delete from db where d.ID = index
//fire deletion event to a DBWrapper object
}
}
This is essentially what I want my output to be:
void Test()
{
DBWrapper dbw = new DBWrapper();
Console.WriteLine(dbw.GetList);
//Apple=1,Banana=2,Cake=3
DeleteDB ddb = new DeleteDB();
ddb.Delete(1);
Console.WriteLine(dbw.GetList);
//Banana=2,Cake=3
}
How do I have one object listen to an event triggered by another object?
You wire up the event handler in the
DbWrapperto the event on theDeleteDB. Here is some code to explain, using what you provided.Please note that your
OnDeletedmethod of theDBWrapperwould need to made public to assign it like this, unless theTest()method is inside of theDBWrapperclass.