0

我创建了一个伪对话框(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;

}

4

1 回答 1

2

如果将新的构造函数重载添加到 Form(或任何派生控件),则需要确保InitializeComponent()调用设计器生成的代码。

使您的新构造函数首先通过以下方式调用默认构造函数: this()

public ReturnDate(String lblCaption) : this()
{
    _lblCaption = lblCaption; 
}
于 2012-06-05T00:04:55.590 回答