我创建了一个伪对话框(FormBorderStyle 属性设置为 FixedDialog 的表单),其中包含一个标签、一个 DatetimePicker 和一个 OK 按钮。OK 按钮的 DialogResult 属性为“OK”
改编自这篇文章:How to return a value from a Form in C#? ,我正在尝试创建一种方法来提示用户选择一个日期,当我的应用程序无法通过文件名确定日期时(有时可以,有时不能,具体取决于文件名是否“格式良好。”
代码如下。
问题是窗体在调用时不显示其控件;并且,它不会显示在屏幕中央,尽管它的 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;
}
}
...我有条件地像这样调用它:
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;
}