【问题标题】:Why do I get a blank form when I debug in C#?为什么我在 C# 中调试时得到一个空白表单?
【发布时间】:2010-10-13 06:35:57
【问题描述】:

我刚刚摆脱了所有编译器错误。问题之一是我不小心重命名了可视表单本身,而不是我的 GUI 上的单个文本框之一。当我去更改我在代码中搞砸的内容时,它似乎又可以工作了。但是,每当我按 F5 进行调试时,我都会得到一个较小的空白窗口作为我的 GUI,而不是我在 Visual Studio 中设计的那个。有什么建议吗?

这是我的主要(表单)类代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace beehive1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        Worker[] workers = new Worker[4];

        workers[0] = new Worker(new string[] { "Nectar collector", "Honey Manufacturing" });
        workers[1] = new Worker(new string[] { "Egg Care", "Baby Bee Tutoring" });
        workers[2] = new Worker(new string[] { "Hive Maintenance", "Sting Patrol" });
        workers[3] = new Worker(new string[] { "Nectar Collector", "Honey Manufacturing",
            "Egg Care", "Baby Bee Manufacturing", "Hive Maintenance", "Sting Patrol" });


        queen = new Queen(workers);
    }

    Queen queen;

    private void assignJob_Click(object sender, EventArgs e)
    {
        if (queen.AssignWork(workerBeeJob.Text, (int)shifts.Value) == false)
            MessageBox.Show("No Workers Are Available To Do The Job " + workerBeeJob.Text + "", "The Queen Bee Says...");
        else
            MessageBox.Show("The job " + workerBeeJob.Text + " will be done in " + shifts.Value + " shifts", "The Queen Bee Says...");

    }

    private void button2_Click(object sender, EventArgs e)
    {
        report.Text = queen.WorkTheNextShift();
    }
}
}

编辑:设计师代码:

namespace beehive1
{
partial class Form1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.shiftLabel = new System.Windows.Forms.Label();
        this.workerBeeJob = new System.Windows.Forms.ComboBox();
        this.jobLabel = new System.Windows.Forms.Label();
        this.shifts = new System.Windows.Forms.NumericUpDown();
        this.groupBox1 = new System.Windows.Forms.GroupBox();
        this.assignJob = new System.Windows.Forms.Button();
        this.nextShift = new System.Windows.Forms.Button();
        this.report = new System.Windows.Forms.TextBox();
        ((System.ComponentModel.ISupportInitialize)(this.shifts)).BeginInit();
        this.groupBox1.SuspendLayout();
        this.SuspendLayout();
        // 
        // shiftLabel
        // 
        this.shiftLabel.AutoSize = true;
        this.shiftLabel.Location = new System.Drawing.Point(287, 26);
        this.shiftLabel.Name = "shiftLabel";
        this.shiftLabel.Size = new System.Drawing.Size(33, 13);
        this.shiftLabel.TabIndex = 0;
        this.shiftLabel.Text = "Shifts";
        // 
        // workerBeeJob
        // 
        this.workerBeeJob.FormattingEnabled = true;
        this.workerBeeJob.Location = new System.Drawing.Point(27, 42);
        this.workerBeeJob.Name = "workerBeeJob";
        this.workerBeeJob.Size = new System.Drawing.Size(121, 21);
        this.workerBeeJob.TabIndex = 1;
        // 
        // jobLabel
        // 
        this.jobLabel.AutoSize = true;
        this.jobLabel.Location = new System.Drawing.Point(24, 26);
        this.jobLabel.Name = "jobLabel";
        this.jobLabel.Size = new System.Drawing.Size(84, 13);
        this.jobLabel.TabIndex = 2;
        this.jobLabel.Text = "Worker Bee Job";
        // 
        // shifts
        // 
        this.shifts.Location = new System.Drawing.Point(290, 42);
        this.shifts.Name = "shifts";
        this.shifts.Size = new System.Drawing.Size(74, 20);
        this.shifts.TabIndex = 3;
        // 
        // groupBox1
        // 
        this.groupBox1.Controls.Add(this.assignJob);
        this.groupBox1.Controls.Add(this.shiftLabel);
        this.groupBox1.Controls.Add(this.workerBeeJob);
        this.groupBox1.Controls.Add(this.jobLabel);
        this.groupBox1.Controls.Add(this.shifts);
        this.groupBox1.Location = new System.Drawing.Point(32, 12);
        this.groupBox1.Name = "groupBox1";
        this.groupBox1.Size = new System.Drawing.Size(384, 150);
        this.groupBox1.TabIndex = 4;
        this.groupBox1.TabStop = false;
        this.groupBox1.Text = "Worker Bee Job Assignments";
        // 
        // assignJob
        // 
        this.assignJob.Location = new System.Drawing.Point(27, 70);
        this.assignJob.Name = "assignJob";
        this.assignJob.Size = new System.Drawing.Size(121, 23);
        this.assignJob.TabIndex = 4;
        this.assignJob.Text = "Assign This Job";
        this.assignJob.UseVisualStyleBackColor = true;
        this.assignJob.Click += new System.EventHandler(this.assignJob_Click);
        // 
        // nextShift
        // 
        this.nextShift.Location = new System.Drawing.Point(422, 38);
        this.nextShift.Name = "nextShift";
        this.nextShift.Size = new System.Drawing.Size(79, 77);
        this.nextShift.TabIndex = 5;
        this.nextShift.Text = "Work The Next Shift";
        this.nextShift.UseVisualStyleBackColor = true;
        this.nextShift.Click += new System.EventHandler(this.button2_Click);
        // 
        // report
        // 
        this.report.Location = new System.Drawing.Point(32, 199);
        this.report.Multiline = true;
        this.report.Name = "report";
        this.report.Size = new System.Drawing.Size(384, 157);
        this.report.TabIndex = 6;
        // 
        // Form
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(539, 398);
        this.Controls.Add(this.report);
        this.Controls.Add(this.nextShift);
        this.Controls.Add(this.groupBox1);
        this.Name = "Form";
        this.Text = "Beehive Management System";
        ((System.ComponentModel.ISupportInitialize)(this.shifts)).EndInit();
        this.groupBox1.ResumeLayout(false);
        this.groupBox1.PerformLayout();
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.Label shiftLabel;
    private System.Windows.Forms.ComboBox workerBeeJob;
    private System.Windows.Forms.Label jobLabel;
    private System.Windows.Forms.NumericUpDown shifts;
    private System.Windows.Forms.GroupBox groupBox1;
    private System.Windows.Forms.Button assignJob;
    private System.Windows.Forms.Button nextShift;
    private System.Windows.Forms.TextBox report;
}
}

也许应用程序不再连接到那个 Form 类?我尝试过 Clean Build 和 ReBuild,但似乎都没有效果。

【问题讨论】:

  • 向我们展示您的 InitializeComponent 方法。
  • 请同时添加设计器代码
  • 我觉得它确实与我的设计器代码有关,但我无法确定问题所在,因为我以前从未使用过该类。

标签: c# winforms visual-studio-2010


【解决方案1】:

空白表示InitializeComponent() 未激活或this.Controls.Add 未正确添加控件。尝试逐步调试并激活所有 CLR 异常,以确保构造函数中没有发生异常。向我们展示表单的构造。

编辑:

应该检查而不是检查如上所示。 现在在调试模式下运行您的表单,看看是否发生任何异常。 请添加您如何称呼您的表格含义:

Form1 newForm=new Form1();

【讨论】:

  • 如何向您展示表单的构造?我已经显示了表单的类以及设计器类。在表单类中,我调用 InitializeComponent();功能
  • 另外,没有编译器错误。它曾经运行良好。
  • 嗨,显示您创建它的表单实例。(可能是对错误表单的调用)。我的意思不是编译器错误,而是运行时异常。去调试->执行->检查CLR异常。
  • 我还是不明白你在说什么。这是我的主要课程。我不是从任何其他班级调用它。这应该是我的表格。我已经检查了 CLR。​​
  • 您可能是从另一个地方调用它,即使您没有意识到它。有一个名为 Program.cs 的文件。这实际上是Main 所在的位置。 Main 中应该有一条类似于Application.Run(new Form1()) 的行。你看到这个了吗?如果您看到Application.Run(new Form())(注意缺少 1),这可能是您遇到问题的地方。
【解决方案2】:

检查您是否在 Main 方法中构造了一个 Form (new Form()) 实例而不是 Form1()

【讨论】:

  • 否,在您创建 GUI 和表单实例的方法中;应该有类似 Application.Run(new Form1());
【解决方案3】:

Visual Studio 有时会出现问题(例如,在重命名项目/表单/目录时)。我自己也在为此苦苦挣扎,直到我发现:

this.Controls.Add(*form object name*); 

Form1.Designer.cs 文件中缺少的行。这些是“自动生成”的行,但显然自动生成并不总是顺利。

我写了一个快速而肮脏的 Python 脚本来尝试解决这个问题。将脚本与 xxx.Designer.cs 文件的副本一起放入新目录并运行它。它将生成一个也许固定的 xxx.Designer.cs.fix 文件。节省了大量的手动复制粘贴。

import os

#get current dir from which the script runs (should also contain the xxx.Designer.cs file)
daDir = os.path.dirname(os.path.abspath(__file__))

#the file extension we're looking for
ext = ".Designer.cs"

#list of all files in the dir from which the script runs
FileList = os.listdir(daDir)

FileToOpen = ""
ObjNameStr = ""
OriginalFileName = "SORRY, AUTO FIXING FAILED"

#the file to open (any first match for .Designer.cs)
for str in FileList:
    if (str.endswith(ext)):
        OriginalFileName = str
        FileToOpen = daDir + "\\" + str
        break

if FileToOpen != "":
    print("File found: " + FileToOpen)
    fileToFix = open(FileToOpen, 'r')

    FormObjStrList = []

    for str in fileToFix:
        # remove whitepaces/leading tabs
        str = str.lstrip()
        # get first part of string: "this.formobjectName"
        str = str.partition(' ')[0]
        if str.startswith("this.") and (str.count('.') == 1):
            ObjNameStr = str
            #add Form object to list if unique:
            if (ObjNameStr not in FormObjStrList) and ("this.components" not in ObjNameStr):
                #No more objects after SuspendLayout property
                if ("this.SuspendLayout" in ObjNameStr):
                    break
                else:
                    FormObjStrList.append("this.Controls.Add(" + ObjNameStr + ");")

    # copy original file to a stringlist that will be the fixed file
    FixedFile = fileToFix.read().splitlines()

    # look op the location to copy the new string list into
    i = 0
    for str in FixedFile:
        if ("this.AutoScaleMode" in str):
            break
        i += 1

    i += 1
    # Create the new xxx.Designer.cs fixed file by adding the extra generated lines
    for str in FormObjStrList:
        FixedFile.insert(i, str)

else:
    print("No fixable file found. ")

print(FormObjStrList)

# Save the new fixed file (manually check/correct this)
FixedFileSave = open(OriginalFileName + ".fix", 'w')
FixedFileSave.write("\n".join(FixedFile))
FixedFileSave.close()

print("New fixed file saved as: " + OriginalFileName + ".fix")
print("Please manually check if the generated file is correct for your project.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2021-11-27
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多