C# User Control - How to tell containing object the control needs data - c#

I am creating a C# WinForms user control. There will be times when the user control will need data from the form it's contained in. How do I go about having the user control tell the form containing it that it needs some data?
Thanks!

You can subscribe the form to an event raised on the UserControl.
Your archiecture dictates where and when you need to subscribe to the data event. We can't answer that without knowing a little more about how your whether you are adding the control at runtime or design time. Each case will require a little derivation. From the perspective of adding your control at runtime, you could do something similar to the following:
// Your sample control
public class MyUserControl : Control
{
public event EventHandler<EventArgs> INeedData;
public Data Data {get; set;}
private class DoSomething()
{
if(INeedData!=null) INeedData(this,null);
}
}
...
// Your Form, in the case that the control isn't already added.
var _myUserControl = new MyUserControl();
private void Form1_Load(object sender, EventArgs e)
{
_myUserControl.INeedData += new EventHandler<EventArgs>(MyUserControl_INeedData);
this.Controls.Add(myUserControl);
}
void MyUserControl_INeedData(object sender, EventArgs e)
{
_myUserControl.Data = SomeData;
}

Create a custom event in the user control and have the form hook into it. If you need custom event arguments, you can create those too.
In user control:
//Define your Custom Event argument
public class MyEventArgs : EventArgs
{
//Define some fields of your custom event argument
private int m_SomeValue = 0;
//Define some properties of your custom event argument
public int SomeValue
{
get { return m_SomeValue; }
set { m_SomeValue = value; }
}
}
//Define the event handler data type
public delegate void MyEventHandler(object sender, MyEventArgs e);
//Define the object which holds the outside event handlers
public event MyEventHandler SomeEvent;
//Define the function which will generate the event
public virtual void OnSomeEvent(MyEventArgs e)
{
if (SomeEvent != null)
SomeEvent(this, e);
}
.
. //Then later in the control
.
{
//We need new data
//Create the event arguments
MyEventArgs newEvent = new MyEventArgs();
//Set the values
newEvent.SomeValue = 17;
//Call the event generating function
OnSomeEvent(newEvent);
}
In your form just use something like:
myControl.SomeEvent += new MyEventHandler(handlerName);
Since your event is public, you should see it in the Properties window of your control as well.
You can fancy up the event using Metadata attributes, but I leave it up to you to discover these.

Create an event on the user control where the event args are editable. Let the form attach a handler to that event, which updates those fields. Use those fields in the OnEvent method.
[untested]
eg.
public delegate void NeedsUserDataEventHandler(object sender, NeedsUserDataEventArgs args);
public class NeedsUserDataEventArgs : EventArgs
{
public UserData UserData { get; set; }
}
// In Control
public event NeedsUserDataEventHandler NeedsUserData;
public void OnNeedsUserData(NeedsUserDataEventArgs args)
{
NeedsUserDataEventHandler handler = NeedsUserData;
if (handler != null) handler(this, args);
// store your data somewhere here
}
// In Form
public override void OnLoad(object sender, EventArgs args)
{
control.NeedsUserData += ControlNeedsUserData;
}
public override void OnClosed(object sender, EventArgs args)
{
control.NeedsUserData -= ControlNeedsUserData;
}
public void ControlNeedsUserData (object sender, NeedsUserDataEventArgs args)
{
args.UserData = // set whatever here
}

Seems a bit vague to me, but:
Make it an event in the containing WinForm, so that every time some data is ready all the subscribers can be notified in a one-to-many model; or make it an event in the subscribed control, in a one-to-one model, in which it calls the container's method that retrieves such data?

It's dependent on when that data needs to be pushed to the UserControl. Are there events taking place on the Form that will drive the need to move data within the UserControl? If so...simply grab your instance at that point and push the data down to the UserControl via a public property.
If this is a case where events are not being used or the Form in some fashion or another "receives the data" then exposing an event on the Form such as...
public event DataHandler ReceivedData;
...and allow the UserControl or any other container to register for the event and receive the data via your custom event args. Pushing the event into the UserControl and forcing the Form to latch onto the UserControl seems backwards since the Form is the initiator of the data.

Related

Calling public event to trigger method in another class in C#

I wanted to ask if this is Event possible in C#. I have not much worked with Events till now.
Say I have a class A which subscribed to a FormClosing Event of a form:
public class A
{
private void f_FormClosed(object sender, FormClosedEventArgs e)
{
//Now here a public Event should be called
}
}
Now there I want a public Event to be called. Let's say now I have another class B which has a certain method.
public class B
{
public void DoSomething()
{
}
}
Now what I want to do:
A Form gets closed so class A is getting notified. There, a public Event gets triggered (which is somewhere in a public class). I want to subscribe my method in class B to this Event so it gets called when that happens. Is this possible? And how is the syntax? I haven't found something useful till now.
Edit: I can't create an instance of class B directly from class A.
Its possible .
Create a new event in A.
Raise the event within the eventhandler f_FormClosed
Subscribe to this event in B.
Within the eventhandler in B call the method DoSomething
For the syntax part you could check MSDN
// A delegate type for hooking up change notifications.
public delegate void ChangedEventHandler(object sender, EventArgs e);
// A class that works just like ArrayList, but sends event
// notifications whenever the list changes.
public class ListWithChangedEvent: ArrayList
{
// An event that clients can use to be notified whenever the
// elements of the list change.
public event ChangedEventHandler Changed;
// Invoke the Changed event; called whenever list changes
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
//you raise the event here.
Changed(this, e);
}
}
Now in your other class do something like this
class EventListener
{
private ListWithChangedEvent List;
public EventListener(ListWithChangedEvent list)
{
List = list;
// Add "ListChanged" to the Changed event on "List".
//This is how we subscribe to the event created in ListWithChangedEvent class
List.Changed += new ChangedEventHandler(ListChanged);
}
// This will be called whenever the list changes.
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires.");
}
}

C# event from a class in a custom usercontrol never fires

I have a class that has an event that's suppose to fire everytime one of it's property changes.
public event EventHandler StructureChanged;
protected virtual void NotifyStructureChanged(EventArgs e)
{
if (StructureChanged != null)
{
StructureChanged(this, e);
}
}
I include NotifyStructureChanged(new EventArgs()); in my set statement in my properties.
whenever it calls the method the StructureChangedis always null. My class is a private member in a custom usercontrol and the class event is registered in the constructor of the usercontrol like so
_pt.StructureChanged += _pt_StructureChanged;
and handled here
void _pt_StructureChanged(object sender, EventArgs e)
{
UpdateControl();
}
What I have so far is a custom class with an event that's a private member of a custom user control. I register my class event in the custom usercontrol. Whenever the class property changes, I update my control to reflect the changes in the class.
What am I doing wrong here? I have a button on my usercontrol and am able to register that event, why can't I register my class event?
If StructureChanged is null than you attach event handler after event was fired (or you are detaching handler somewhere).
Also don't pass EventArgs - its just useless dummy parameter.
public event EventHandler StructureChanged;
protected virtual void OnStructureChanged()
{
if (StructureChanged != null)
StructureChanged(this, EventArgs.Empty);
}
And call this method in setter:
public Foo Bar
{
get { return _bar; }
set {
if (_bar == value)
return;
_bar = value;
OnStructureChanged();
}
}

C# delegate and event in UserControl

I have UserControl similar to ListView. I want to create event machining delete item from ListView.
I doing so. But I do not know how to go on.
public partial class ImagesSetEditor : UserControl
{
public delegate void ImageRemovedEventHandler(object sender, ImagesSetEditor e);
public event ImageRemovedEventHandler ImageRemovedEvent;
You do not need to create a new delegate for conforming with the event based pattern. Create a simple event in your control as such:
public event EventHandler ImageRemoved;
if you need any custom arugments passed on, create a class that derives from EventArgs as such:
public class ImageRemovedEventArgs : EventArgs
{
public int Index; //for example
}
and then declare the event as such:
public event EventHandler<ImageRemovedEventArgs> ImageRemoved;
You would then fire the event as such:
if (ImageRemoved != null) ImageRemoved(this, new ImageRemovedEventArgs() { Index = yourValue });
It is important to check that ImageRemoved != null, because it will throw an exception if the event has no subscribers.

Pass Value Selected From a User Control to a Parent

I have a Winform dialog that contains several user controls - all of them are some sort of Datagridview. The main parent has details about a user, and the user controls each have additional details on that person. When my Dialog first loads all of the UserControls work but I am trying to figure out how to update the UserControl2 based on a position change in UserControl1.
So, I am trying to select a row in UserControl1 and have the data in UserControl2 update based on a value that I just selected.
I have tried using MouseDownEvents on the UserControl1 and BindingSourcePositionChanged but I can't figure out how to get the value selected back to my parent form and then use that value to refresh the other datagrids?
I looked at delegates and events but I guess the lack of sleep is making it incredibly hard to comprehend. I understand that I need to create my delegate and event on the UserControl1 and then somehow call it on my mainform but that's where I get stuck and have no clue where to start.
Is this the right direction? Or is there another way to get this done? Can anyone offer up any suggestions on how this works?
Yes this is the correct approach something like the following will provide an event handler that you can use to the retrieve a public property from the UserControl:
public class SomeClass : BaseControl
{
public event EventHandler PersonSelected;
public string Name{get;set;}
protected void FindUser()
{
var find = new Button {ID = (ToString() + "search"), Text = "Search"};
find.Click += delegate(object sender, EventArgs e)
{
if (PersonSelected!= null)
{
//forward this event to the page's event handler
PersonSelected(this, e);
}
};
}
}
public class SomeOtherClass : Page
{
public void Main()
{
var sp = (SomeClass)Control;
sp.PersonSelected += BtnClick;
}
public void BtnClick(object sender, EventArgs e)
{
//Get some value from the (SomeClass)Control here
}
}

What is the correct way to change properties in a parent form from a child form?

I was just wondering if I'm doing this the correct way. I have 2 forms a parent form and a child form (options dialog). To change a property in my parent form from my child form I use code like this:
// Create an array of all rich textboxes on the parent form.
var controls = this.Owner.Controls.OfType<RichTextBox>();
foreach (var item in controls) {
if (chkDetectUrls.Checked)
((RichTextBox)item).DetectUrls = true;
else
((RichTextBox)item).DetectUrls = false;
}
I only have one RichTextBox on my form. It seems silly to have to loop through a array of 1 control. Is this the correct way to do it or is there an easier way?
It's not appropriate to change properties in a parent form at all. Instead, your child form should raise an event which the parent form listens for, and changes its own value accordingly.
Manipulating the parent form from the child creates a two-way coupling - the parent form owns the child, but the child also has intimate knowledge and dependency on the parent form. Bubbling is the established solution to this, as it allows information to flow upwards ('bubbling') while avoiding any strict coupling.
Here is the most basic example of eventing. It does not include passing specific information in the event (which is what you may need) but covers the concept.
In your child form:
//the event
public event EventHandler SomethingHappened;
protected virtual void OnSomethingHappened(EventArgs e)
{
//make sure we have someone subscribed to our event before we try to raise it
if(this.SomethingHappened != null)
{
this.SomethingHappened(this, e);
}
}
private void SomeMethod()
{
//call our method when we want to raise the event
OnSomethingHappened(EventArgs.Empty);
}
And in your parent form:
void OnInit(EventArgs e)
{
//attach a handler to the event
myChildControl.SomethingHappened += new EventHandler(HandleSomethingHappened);
}
//gets called when the control raises its event
private void HandleSomethingHappened(object sender, EventArgs e)
{
//set the properties here
}
As I said above, you probably need to pass some specific information in your event. There's a few ways we can do this, but the simplest one is to create your own EventArgs class and your own delegate. It looks like you need to specify whether some value is set to true or false, so let's use that:
public class BooleanValueChangedEventArgs : EventArgs
{
public bool NewValue;
public BooleanValueChangedEventArgs(bool value)
: base()
{
this.NewValue = value;
}
}
public delegate void HandleBooleanValueChange(object sender, BooleanValueChangedEventArgs e);
We can change our event to use these new signatures:
public event HandleBooleanValueChange SomethingHappened;
And we pass our custom EventArgs object:
bool checked = //get value
OnSomethingHappened(new BooleanValueChangedEventArgs(checked));
And we change our event handling in the parent accordingly:
void OnInit(EventArgs e)
{
//attach a handler to the event
myChildControl.SomethingHappened += new HandleBooleanValueChange(HandleSomethingHappened);
}
//gets called when the control raises its event
private void HandleSomethingHappened(object sender, BooleanValueChangedEventArgs e)
{
//set the properties here
bool value = e.NewValue;
}

Categories