UserControl并打开设计器C#winforms抛出错误

时间:2018-07-24 15:48:27

标签: c# winforms visual-studio-2017

如果我没有按照正确的标准发帖,请原谅我,但这是我的问题。 我正在使用VS2017,C#Winforms开发。我创建了一个用户控件,它只是一个文本框。我正在此文本框中捕获一些事件,并根据发生的事情(例如进入/离开和只读模式)更改颜色。昨天,当我设计表单时,一切都很好。今天,我回到机器上,现在无法打开设计器。我收到一条错误消息:“设计器无法在第470行处理该代码,有关详细信息,请参见任务列表。方法'InitializeComponent'中的代码由设计器生成,不应手动修改。请删除所有更改并尝试再次打开设计师。”

这是引起问题的设计师代码

this.txtName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.txtName.BackColor = System.Drawing.Color.Transparent;
        this.txtName.Location = new System.Drawing.Point(139, 23);
        this.txtName.Name = "txtName";
        this.txtName.PasswordChar = "\0";
        this.txtName.ReadOnly = false;
        this.txtName.Size = new System.Drawing.Size(303, 19);
        this.txtName.TabIndex = 2;

这是我的UserControl的代码

    public partial class TextBoxCustom : UserControl
{
    Color onEnter = Color.Beige;
    private Color readOnly = Color.Silver;
    Color onLeave = Color.White;
    public string Text
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text = value;
        }

    }

    public string Name
    {
        get { return textBox1.Name;}
        set { textBox1.Name = value; }
    }
    public bool ReadOnly
    {
        get { return textBox1.ReadOnly; }
        set
        {
            textBox1.ReadOnly = value;
            if (value == true)
            {
                textBox1.BackColor = readOnly;
            }
        }
    }
    public string PasswordChar
    {
        get { return textBox1.PasswordChar.ToString(); }
        set { textBox1.PasswordChar = Convert.ToChar(value); }
    }
    public void Clear()
    {
        Text = "";
    }
    public TextBoxCustom()
    {
        InitializeComponent();
    }

    private void TextBoxCustom_Leave(object sender, EventArgs e)
    {
        textBox1.BackColor = (textBox1.ReadOnly) ? readOnly : onLeave;
    }

    public void SetDataBindings(BindingSource source,string model)
    {

         textBox1.DataBindings.Add(new Binding("Text", source, model, true, DataSourceUpdateMode.OnPropertyChanged));
    }


    private void TextBoxCustom_Enter(object sender, EventArgs e)
    {

        textBox1.BackColor = (textBox1.ReadOnly)? readOnly: onEnter;
    }


}

现在,如果我要注释掉第470行,就像我说的那样,我将在另一行收到错误消息。我也注释掉了整个设计器代码块,并且能够打开设计器,但是当我尝试重新使用它时,代码只是重新生成并再次引发错误。我曾尝试清洁/重建/重新启动Visual Studio。我已经删除了Bin和Obj文件夹,甚至已经确保UserControl是主应用程序中引用的它自己的单独项目的一部分。

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

设计器中的以下代码行:

this.txtName.PasswordChar = "\0";

产生以下消息:

  

“字符串必须恰好是一个字符长。”

TextBox控件使用Char作为PasswordChar属性的数据类型,而不是字符串。切换它应该可以解决问题。

相关问题