为什么我的伪对话框形式隐藏了它的“魅力”并忽略了它自己的属性?

时间:2012-06-04 23:31:06

标签: c# winforms dialog

我创建了一个伪对话框(FormBorderStyle属性设置为FixedDialog的表单),其中包含一个标签,一个DatetimePicker和一个OK按钮。 OK按钮的DialogResult属性为“OK”

改编自这篇文章:How to return a value from a Form in C#?,我正在尝试创建一种方法来提示用户选择一个日期,当我的应用程序无法按文件名排除日期时(有时它可以,有时它不能,取决于文件名是否“格式良好”。

代码如下。

问题是表单在调用时不显示其控件; AND,它不显示在屏幕的中央,虽然它的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;

}

1 个答案:

答案 0 :(得分:2)

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

首先通过: this()

让新构造函数调用默认构造函数
public ReturnDate(String lblCaption) : this()
{
    _lblCaption = lblCaption; 
}