【发布时间】:2011-07-21 17:04:05
【问题描述】:
我正在尝试将控件动态地拖放到我的控件树中。例如:
在特定条件下,我调用:
private void resetPanel()
{
Panel.Controls.Clear();
Panel.Controls.Add(Image);
Panel.Controls.Add(HiddenField);
}
我的主要目标是如何让添加的控件在回发中持续存在?
当我使用文本框和标题调用另一个类似的函数时,它会完美地保留下来。但是,图像会丢失其 URL 和属性。
我知道要使动态控件持久存在,您必须将其添加到 Init 中,并且您必须对控件树负责,因此需要在每次回发时将动态控件添加到树中。
那么为什么它适用于跨回传的文本框和标签,但您不能为图像和隐藏字段添加控件?
谢谢, 布赖恩
--更新和解决方案--
我在我的代码中发现了一个错误,并且 HiddenField 值在回发中确实存在。我选择的解决方案是使用 ViewState 来保存值,然后在每次回帖时恢复我的动态控件。
--编辑--
感谢您的回复,由于我的问题可能有更好的解决方案,这里有一些代码有望显示我如何调用该方法以及为什么需要这样做。
public void resetTitlePanel()
{
// Restylize the panel to initial state
TitlePanel.Controls.Clear();
TitlePanel.BorderColor = System.Drawing.Color.Maroon;
TitlePanel.BorderStyle = BorderStyle.Dashed;
TitlePanel.Enabled = true;
// Set the new control properties to initial state
Label TitleLabel = new Label();
TitleLabel.ID = "TitleLabel";
TextBox TitleTxtBox = new TextBox();
TitleTxtBox.ID = "TitleTxtBox";
// Add the new controls to the container
TitlePanel.Controls.Add(TitleLabel);
TitlePanel.Controls.Add(TitleTxtBox);
// Set the reference of this to the new dynamic control
this.TitleLabel = TitleLabel;
this.TitleTxtBox = TitleTxtBox;
}
public void resetImagePanel()
{
// Restylize the panel to initial state
ImagePanel.Controls.Clear();
ImagePanel.BorderColor = System.Drawing.Color.Blue;
ImagePanel.BorderStyle = BorderStyle.Dashed;
ImagePanel.HorizontalAlign = HorizontalAlign.NotSet;
// Set the new control properties to initial state
Image AddImage = new Image();
AddImage.ImageUrl = "~/Resources/Icons/picture_add.png";
AddImage.ID = "AddImage";
HiddenField HiddenImage = new HiddenField();
HiddenImage.ID = "HiddenImage";
// Add the new controls to the container
ImagePanel.Controls.Add(AddImage);
ImagePanel.Controls.Add(HiddenImage);
// Set the reference of this to the new dynamic control
this.AddImage = AddImage;
this.HiddenImage = HiddenImage;
}
调用方法:
private void copyFromSlide(TemplateControl destination, Template source)
{
// Reset the template
destination.resetTitlePanel();
destination.resetImagePanel();
destination.Title = source.Title;
// Find the path from the database and assign it to the control
destination.ImagePath = modData.getImagePath((int)source.ImageID);
}
所以...我知道代码很复杂,也许比它应该的复杂。此外,我只是一个初学者,所以它可能质量较差,对此我深表歉意。
主要注意事项是:
- 有 2 个用户控件相互交互。
- 这完全适用于 !IsPostback。
- ViewStateEnable 默认为 true,即使我明确指定它为 true,我也会得到相同的结果。
- 这完全适用于由标签和文本框组成的标题面板,两者都保留其值。
- 我知道我将静态和动态控件混合在一起。我习惯了 C,所以我不确定是否可以将对象指针移动到新的动态对象。
问题是,在分配图像路径时,该值不会在回发时保留。
我需要删除并重新添加控件,因为在特定条件下我将删除控件并添加标签,如上所述,这没有问题。我认为我不需要再次初始化控件的原因是因为我正在添加一个有根面板,如下所示:
我希望这会增加一些清晰度。
再次感谢,
-布赖恩
【问题讨论】:
-
您是说您还添加了动态文本框和标签以及动态图像和隐藏字段?您是说添加动态文本框和标签并且它们会持续存在,而图像和隐藏字段则不会?
-
嗨 Gangelo,这或多或少就是我要说的。但是,除了图像和隐藏字段之外,文本框和标签是在一个函数中添加的。