简体   繁体   中英

Accessing variables in other Windows Form class C#

I want to push my var selectedDate from frmMain so it can use in frmEvent .

The var will make a label in frmEvent that var value. Here is my code:

private void monthCalendar1_SelectedDate(object sender, DateRangeEventArgs e)
    {
        var selectedDate = (DateTime.Parse(e.Start.ToShortDateString())).Day;
        frmEvent frmE = new frmEvent();
        frmE.Show();
    }

You can do one of two things. Either add a date to the constructor of frmEvent , or add a property to frmEvent and set it before calling .Show() .

Constructor way:

public partial class frmEvent : Form
{
  private int SelectedDate;
  public frmEvent(int selectedDate)
  {
    InitializeComponent();
    SelectedDate = selectedDate;
  }
}

public partial class frmMain : Form
{
    private void monthCalendar1_SelectedDate(object sender, DateRangeEventArgs e)
    {
        var selectedDate = (DateTime.Parse(e.Start.ToShortDateString())).Day;
        frmEvent frmE = new frmEvent(selectedDate);
        frmE.Show();
    }
}

Property way:

public partial class frmEvent : Form
{
    public int SelectedDate { get; set; }
    public frmEvent()
    {
        InitializeComponent();
    }
}

public partial class frmMain : Form
{
    private void monthCalendar1_SelectedDate(object sender, DateRangeEventArgs e)
    {
        var selectedDate = (DateTime.Parse(e.Start.ToShortDateString())).Day;
        frmEvent frmE = new frmEvent();
        frmE.SelectedDate = selectedDate;
        frmE.Show();
    }
}

Just treat the forms like normal classes, mostly because that is what they are and can be treated as such, do not overthink it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM