Question

I am hoping someone can help me out. I have created a usercontrol in C# for use on a Winform. The control contains various controls including a monthCalendar control however the monthCalendar control is where my problem lies.

I want the parent form that holds my usercontrol to trigger a block of code to query a database using linq when the dateSelected event of the monthCalendar within the usercontrol is triggered. The idea being that the usercontrol should not be aware of the data access side of things so that the usercontrol can be used in other projects.

What I was hoping was that there was a way that I could make the dateSelected event available to the parent form; I have done this successfully with click events etc for other controls I just can't seem to make this work for the monthCalendar as DateSelected uses DateRangeEventHandler rather than the standard EventHandler.

I hope this is clear as i have been around the block with this one so i'm not sure what makes any sense any more :) Any help or advice in how I could go about coding this would be very much appreciated.

Was it helpful?

Solution

Same way you would with the Button events.

In your UserControl, it would look something like this:

public event DateRangeEventHandler DateChanged {
  add { monthCalendar1.DateChanged += value; }
  remove { monthCalendar1.DateChanged -= value; }
}

Then in your form, like all controls with events:

userControl11.DateChanged += userControl11_DateChanged;

void userControl11_DateChanged(object sender, DateRangeEventArgs e) {
  // do something...
}

OTHER TIPS

You can make MonthCalendar public in your UserControl and then in your Form just subscribe to the event using:

this.userControl.Monthcalender.DateSelected += new DateRangeEventHandler(Monthcalender_DateSelected)

or you can create a new event in your UserControl which will be raised on MonthCalendar.DataSelected. and in your Form subscribe to that event, something like:

UserControl:

 public UserControl1()
        {
            InitializeComponent();                
            this.monthCalendar1.DateSelected += new DateRangeEventHandler(monthCalendar1_DateSelected);
        }

        public void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
        {
            OnSeChanged(e);
        }

        public event DateRangeEventHandler SeChanged;

        protected virtual void OnSeChanged(DateRangeEventArgs e)
        {
            if (SeChanged != null)
            {
                SeChanged(this, e);
            }
        }

Form:

 userControl11.SeChanged += new DateRangeEventHandler(userControl11_SeChanged);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top