对象与目标类型不匹配

问题描述 投票:6回答:4

我有一个TableLayoutPanel,其中有一个PictureBox控制网格。我正在尝试找到一种快捷方式将它们全部更改为Label控件,而不是手动删除每个控件并在每个单元格中放置新控件。

我以为我可以进入设计器代码并使用Label查找/替换PictureBox,但现在我得到了一个

“对象与目标类型不匹配”

Visual Studio错误列表中的错误。我现在也无法查看设计器页面。这是不允许的?如果允许,那么正确的方法是什么?

c# .net winforms label picturebox
4个回答
14
投票

如果您仔细查看生成的代码:

label1

this.label1 = new System.Windows.Forms.Label();
// 
// label1
// 
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(134, 163);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 1;
this.label1.Text = "label1";

pictureBox1

this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
// 
// pictureBox1
// 
this.pictureBox1.Location = new System.Drawing.Point(97, 75);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(100, 50);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;

我的猜测是

((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();

由你改变成:

((System.ComponentModel.ISupportInitialize)(this.label1)).BeginInit();

这不起作用,并导致设计师的问题。 Object does not match target type.

所以,应用你已经做过的更改,删除如下行:

((System.ComponentModel.ISupportInitialize)(this.label1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.label1)).EndInit();

而且我觉得你很高兴。


1
投票

不要更改设计器代码。这些东西是自动生成的。您的更改不仅会导致意外行为,而且它们也会被覆盖。

我会尝试对你的表单进行更改或2,或者你的设计师背后的任何东西,并希望它重新生成它的所有代码。


1
投票

您可以删除设计器中的所有图片框,然后在_load事件(或其他方便的事件)中添加所有标签。这样下次更改会更容易。


0
投票

正如Haxx所说,你将不得不清理PictureBox所需的额外初始化。您收到的错误是界面转换错误。在你的情况下,正如Haxx猜测的那样,Label控件没有实现ISupportInitialize接口。

与大多数人不同,我不怕为了方便而改变设计师代码,因为你正在做的事情,这样做是可以的。只需知道你的对象,在这之前办理登机手续,并且不要在那里放置自定义代码!

© www.soinside.com 2019 - 2024. All rights reserved.