简体   繁体   English

C#one表单即时访问控件

[英]C# one form instant access controls

I have the following code that checks if an instant of the form is open. 我有以下代码检查表单的瞬间是否打开。 However, I cant access the controls (DataGridView dgvPDF), if the form is already opened: 但是,如果表单已经打开,我无法访问控件(DataGridView dgvPDF):

            Form frmPDF = Application.OpenForms["frmPDFs"];
            if (frmPDF != null)
            {
                frmPDF.Focus();
                frmPDF.dgvPDF.DataSource = PDF.CheckPDFs(Files, frmPDF.tblPDFs); <--- red squiggly lines

            }
            else
            {
                frmPDFs frmPDF1 = new frmPDFs();
                frmPDF1.Show();
                frmPDF1.dgvPDF.DataSource = PDF.CheckPDFs(Files, frmPDF1.tblPDFs);
            }

The error message was: 错误消息是:

Error 1 'System.Windows.Forms.Form' does not contain a definition for 'dgvPDF' and no extension method 'dgvPDF' accepting a first argument of type 'System.Windows.Forms.Form' could be found (are you missing a using directive or an assembly reference?) 错误1'System.Windows.Forms.Form'不包含'dgvPDF'的定义,并且没有可以找到接受类型'System.Windows.Forms.Form'的第一个参数的扩展方法'dgvPDF'(你错过了吗?使用指令或程序集引用?)

This is a strongly typed variable: 这是一个强类型变量:

Form frmPDF = Application.OpenForms["frmPDFs"];

So frmPDF is now an instance of type Form , which is the base class for your form. 所以frmPDF现在是Form类型的实例,它是Form基类 It's not the type of your actual form. 不是您实际形式的类型。 (It's an instance of your specific form type, but that instance is known to the compiler as its base type in this case.) (它是您的特定表单类型的实例,但在这种情况下,编译器将该实例称为其基本类型。)

What type is your actual form? 你的实际形式是什么类型的? Let's assume for a moment it's Form1 . 我们暂时假设它是Form1 Then make it that type: 然后使它类型:

Form1 frmPDF = (Form1)Application.OpenForms["frmPDFs"];

Then you can access public members of the type Form1 on frmPDF . 然后,您可以访问frmPDF Form1类型的公共成员。


Edit: According to your comment below, the type is frmPDFs . 编辑:根据您在下面的评论,类型是frmPDFs So use that: 所以使用:

frmPDFs frmPDF = (frmPDFs)Application.OpenForms["frmPDFs"];

Edit: Casting might be dangerous, by the way. 编辑:顺便说一句,施法可能很危险。 You could include some type checking and handle errors more gracefully: 您可以包含一些类型检查并更优雅地处理错误:

frmPDFs frmPDF = Application.OpenForms["frmPDFs"] as frmPDFs
if (frmPDF == null)
{
    // the form was the wrong type, something isn't right
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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