I have a calendar control on one form (statsform) that I am calling from another form exportform:
here is the code in statsform where I instantiate exportform:
private void export_Click(object sender, EventArgs e)
{
if (formIsHidden == 0)
{
ExportForm exportForm = new ExportForm();
exportForm.Show();
formIsHidden = 1;
}
}
I update the date in the calendar control in statsform every time it is clicked:
public void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
dateFromLabel.Text = dateFromCalendar.SelectionStart.ToString("dd/MM/yyyy");
}
public void monthCalendar2_DateChanged(object sender, DateRangeEventArgs e)
{
dateToLabel.Text = dateToCalendar.SelectionStart.ToString("dd/MM/yyyy");
}
Here is the code from form2 (trying to get selectionStart Property and use it)
(On button click)
statsform statsform = new statsform();
string startDate = statsform.dateFromCalendar.SelectionStart.ToString("yyyy-MM-dd 00:00:00");
string endDate = statsform.dateToCalendar.SelectionStart.ToString("yyyy-MM-dd 23:59.00");
(Pass date to SQL Queries)
However, the selected date is not passed to exportform, only the current date is passed when i create a breakpoint and inspect the strings.
Is it because I am creating a new instance of the form? How can I pass the user selected date form the form to the second form?
statsform(create Calendar) -> exportform (button click event - retrieve selectedDate from statsform calendar control)
My solution:
public ExportForm(statsform parent)
{
InitializeComponent();
statsform = parent;
}
Allowed me to use the existing instance of the form. I needed the (this) in the constructor though so thanks for all the help.
You could set up a parameter on your exportform’s constructor when you instantiate it to pass a reference to your first form, then reference those properties directly.
So inside your exportform’s class
private statsform _statsform = null;
public exportform(statsform caller) {
_statsform = caller;
}
Then when you instantiate it
ExportForm exportForm = new ExportForm(this);
And from your button click code you reference the labels in your statsform
var fromDate = _statsform.dateFromCalendar.... etc
More info on constructors here https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors