I’ve created a pseudo dialog (form with FormBorderStyle property set to FixedDialog) that contains a label, a DatetimePicker, and an OK button. The OK button’s DialogResult property is “OK”
Adapted from this post: How to return a value from a Form in C#?, I’m trying to create a way to prompt the user to select a date when my app can’t suss out the date by the filename (sometimes it can, sometimes it can’t, depending on whether the filename is “well formed.”
The code is below.
The problem is that the form does not display its controls when it is invoked; AND, it does not display in the center of the screen, although its StartPosition = CenterScreen…???
public partial class ReturnDate : Form {
public DateTime ReturnVal { get; set; }
private String _lblCaption;
public ReturnDate() {
InitializeComponent();
}
public ReturnDate(String lblCaption) {
_lblCaption = lblCaption; // "Object not set to an instance of an object" if I try to set the Label here directly
}
private void buttonOK_Click(object sender, EventArgs e)
{
this.ReturnVal = dateTimePicker1.Value.Date;
this.Close();
}
private void ReturnDate_Shown(object sender, EventArgs e) {
labelCaption.Text = _lblCaption;
}
}
…and I conditionally invoke it like so:
public static DateTime getDateTimeFromFileName(String SelectedFileName) {
// Expecting selected files to be valid pilsner files, which are expected
// to be of the format "duckbilledPlatypus.YYYY-MM-DD.pil" such as:
// "duckbilledPlatypus.2011-06-11.pil"
const int DATE_BEGIN_POS = 19;
const int DATE_LENGTH = 10;
String substr = string.Empty;
if (SelectedFileName.Length >= DATE_BEGIN_POS + DATE_LENGTH) {
substr = SelectedFileName.Substring(DATE_BEGIN_POS, DATE_LENGTH);
}
DateTime dt = DateTime.Now;
if (!(DateTime.TryParse(substr, out dt))) {
using (var dtpDlgForm = new ReturnDate("Please select the Date that the file was created:")) {
DialogResult dr = dtpDlgForm.ShowDialog();
if (dr == DialogResult.OK) {
dt = dtpDlgForm.ReturnVal;
}
}
}
return dt;
}
If you add a new constructor overload to a Form (or any derived Control), you need to make sure that the designer-generated code in
InitializeComponent()gets called.Make your new constructor call the default constructor first via
: this():