OnItemInstered, OnItemUpdated the same code behind
I need to associate different methods of the control with exact same code. I'm doing it like this now:
protected void dgvProperty_ItemInserted(object sender, GridInsertedEventArgs e)
{
BindItems();
}
protected void dgvProperty_ItemDeleted(object sender, GridDeletedEventArgs e)
{
Binditems();
}
protected voi开发者_StackOverflowd dgvProperty_ItemUpdated(object sender, GridUpdatedEventArgs e)
{
BindItems();
}
It feels wrong. How can I avoid repetitions?
I don't think that there is anything 'wrong' with the code you are showing above, but it IS possible to consolidate this logic
If the dgv object is a class under your control you can have it raise another event that gets raised whenever an items is inserted, deleted, or updated. Then you can simply listen to this event. Or, you can subclass the dgv object to add the behavior shown above.
Edit: Here's an example. I did a quick google on the event args in your sample and I'm guessing you're using the Telerik RadGrid so I'll base my example on that, though the principal is generic.
public class ExampleGrid : RadGrid
{
public ExampleGrid() : base()
{
base.ItemInserted += (o, e) => NotifySomethingChanged();
base.ItemDeleted += (o,e) => NotifySomethingChanged();
base.ItemUpdated += (o,e) => NotifySomethingChanged();
}
public event EventHandler SomethingChanged;
private void NotifySomethingChanged()
{
var handler = this.SomethingChanged;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
Now you can listen to the SomethingChanged event. This is only marginally better than attaching the 3 event handlers in your control, but if you're doing something like this frequently it could be worth it
Unfortunately not since the arguments for each event are different. If GridXXXEventArgs all inherit from the same class (I.e. GridEventArgs) then you could do it a bit neater but I doubt this is the case here.
You are doing the correct thing by using a single method that is called from each event.
精彩评论