C#更改标签的ForeColor会隐藏其他所有内容

时间:2016-07-26 08:46:56

标签: c# winforms

我目前正在处理文件资源管理器。 现在我想更改一个标签的ForeColor。 但是只要我为它添加代码,其他一切都会消失。

lblpath.ForeColor = ColorTranslator.FromHtml("00ff00");

当我启动应用程序时,Form1将为空。

我不知道是否应该发布我的代码,因为它相当多,而且我不知道哪些部分是相关的......

编辑: 我使用此代码的方法:

    private void initiateGUI()
    {

        this.Text = "Explorer";
        this.BackColor = ColorTranslator.FromHtml("#1a1a1a");

        oneup = new Button();
        oneup.Location = new Point(455, 12);
        oneup.Parent = this;
        oneup.Visible = true;
        oneup.MouseClick += oneup_click;
        oneup.Text = "UP";
        oneup.Width = 40;
        oneup.Height = 20;

        cmdrefresh = new Button();
        cmdrefresh.Location = new Point(500, 12);
        cmdrefresh.Parent = this;
        cmdrefresh.Visible = true;
        cmdrefresh.MouseClick += refresh_click;
        cmdrefresh.Text = "Refresh";
        cmdrefresh.Width = 55;
        cmdrefresh.Height = 20;

        lblfolder.Location = new Point(475, 39);
        lblfolder.Font = font;
        //lblfolder.ForeColor = Color.Blue;
        lblfolder.Parent = this;
        lblfolder.Height = 13;
        lblfolder.Text = "Folders";

        lblfile.Location = new Point(12, 39);
        lblfile.Font = font;
        //lblfile.ForeColor = ColorTranslator.FromHtml("#00ff00");
        lblfile.Parent = this;
        lblfile.Height = 13;
        lblfile.Text = "Files";

        lblpath.Location = new Point(12, 15);
        lblpath.Font = font;
        lblpath.ForeColor = ColorTranslator.FromHtml("#00ff00");
        lblpath.Parent = this;
        lblpath.Height = 13;
        lblpath.Width = 30;
        lblpath.Text = "Path";

        scrollfolder.AutoScroll = false;
        scrollfolder.HorizontalScroll.Enabled = false;
        scrollfolder.HorizontalScroll.Visible = false;
        scrollfolder.HorizontalScroll.Maximum = 0;
        scrollfolder.AutoScroll = true;
        scrollfolder.Parent = this;
        scrollfolder.Height = 390;
        scrollfolder.Width = 220;
        scrollfolder.Location = new Point(x2 - 10, y - 10);

        scrollfiles.AutoScroll = false;
        scrollfiles.HorizontalScroll.Enabled = false;
        scrollfiles.HorizontalScroll.Visible = false;
        scrollfiles.HorizontalScroll.Maximum = 0;
        scrollfiles.AutoScroll = true;
        scrollfiles.Parent = this;
        scrollfiles.Height = 390;
        scrollfiles.Width = 420;
        scrollfiles.Location = new Point(x - 10, y - 10);
    }

2 个答案:

答案 0 :(得分:2)

您在颜色定义中缺少#。它应该是:

lblpath.ForeColor = ColorTranslator.FromHtml("#00ff00");
如果使用ColorTranslator.FromHtml

"00ff00"将抛出异常

答案 1 :(得分:1)

为什么不使用设计师设置颜色?

您在哪里将此代码添加到构造函数中?最有可能的是,该语句在InitializeComponents有机会运行之前抛出异常 - 如果您在InitializeComponents之前将代码添加到构造函数中,那很可能是lblpath还没有存在,所以你得到NullReferenceException。尝试启用"打破所有异常"在调试器中,调试Winforms应用程序非常方便,因为不再会误解错误。

使用设计师设置颜色,你就可以了。