简体   繁体   中英

C# Windows Forms Type Conversion Error

Right now, I am learning C# from a textbook. In one of the examples in the chapter I'm currently stuck on, Windows Forms, I am instructed to enter the following code to create a simple window:

namespace WinForms {

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;

public class HelloWindowsForms : System.Windows.Forms.Form
{
    private System.Windows.Forms.Label label1;

    public HelloWindowsForms()
    {
        this.label1 = new System.Windows.Forms.Label();

        label1.Location = new System.Drawing.Point(8,8);
        label1.Text = "Hello Windows Forms!";
        label1.Size = new System.Drawing.Size(408,48);
        label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 24f);
        label1.TabIndex = 0;
        label1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; //this is the problem

        this.Text = "Hello World";
        this.MaximizeBox = false;
        this.AutoScaleBaseSize = new System.Drawing.Size(5,13);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
        this.MinimizeBox = false;
        this.ClientSize = new System.Drawing.Size(426,55);
        this.Controls.Add(label1);
    }

    public static void Main(string[] args)
    {
        Application.Run(new HelloWindowsForms());
    }
    }
}

On the problem line(specified in single line comment) I get this error when running this program:

Cannot implicitly convert type 'System.Windows.Forms.HorizontalAlignment' to 'System.Drawing.ContentAlignment'. An explicit conversion exists (are you missing a cast?) (CS0266)

Other sources online say I need to cast, but I can't figure out what to cast or what to cast it as. I tried skipping ahead and completing the chapter, but I get similar Cannot implicitly convert type errors when trying to do all of the examples. Can someone help me figure out how to fix this?

You are using the wrong enum. You are using a System.Windows.Forms.HorizontalAlignment enum when the TextAlign property is calling for a System.Drawing.ContentAlignment enum. Try this:

label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

I bumped in the same problem and figured this out,

If you are using

Label

then use this:

this.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

I think you are using

TextBox

Therefore, use:

this.textbox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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