【问题标题】:.Net designer.cs not updated when control is in ItemTemplate当控件位于 ItemTemplate 中时,.Net Designer.cs 未更新
【发布时间】:2010-02-10 23:53:47
【问题描述】:

我有一个简单的表格。假设一个文本框和一个按钮。

如果这些项目放置在 aspx 页面上,它们会自动添加到 *.designer.cs 文件中,并且可以在我后面的 C# 代码中引用。就像它应该做的那样。

当我将这些项目放在 FormView 控件中时,就会出现问题。此时,它们的所有痕迹都将从 Designer.cs 文件中删除,并且使用这些控件编写的任何代码现在都会给出“在当前上下文中不存在”错误。 FormView 控件本身留在设计器代码中。如果我重新添加它们,它们将不会粘住。如果我删除 Designer.cs 并让它重新制作,它只是在没有控件的情况下重新制作。

有什么线索吗?

【问题讨论】:

  • ItemTemplate 没有“id”和“runat”属性。

标签: c# designer itemtemplate


【解决方案1】:

如果您只处理 1 个 EditItemTemplate(或任何模板),则另一种方法是从 FormView 继承并覆盖将 TemplateInstance attribute 设置为 TemplateInstance.Single。像这样:

public class FormView : System.Web.UI.WebControls.FormView
{
  [Browsable(false), 
  DefaultValue((string)null), 
  PersistenceMode(PersistenceMode.InnerProperty), 
  TemplateContainer(typeof(FormView), BindingDirection.TwoWay),
  TemplateInstance(TemplateInstance.Single)]
  public override ITemplate EditItemTemplate
  {
    get { return base.EditItemTemplate; }
    set { base.EditItemTemplate = value; }
  }
}

如果您在页面中使用该 FormView 控件,EditItemTemplate 中的控件将出现在您的设计器中,并且也可以在代码隐藏中直接访问。

【讨论】:

    【解决方案2】:

    我是通过稍微不同的方式搜索答案才弄明白的。您必须使用 FindControl,因为这些项目位于 FormView 控件中。见例子:

    posting.Title = ((TextBox)FormView1.FindControl("txtTitle")).Text;

    【讨论】:

      【解决方案3】:

      如果要将控件添加到 FormView,请使用 ItemTemplate,并将所需的控件拖放到 itemTemplate 上。然后你就可以从后面的代码中访问这些控件了。

      这是一个示例

      <asp:FormView >
          <ItemTemplate id="MyControl" runat="server">
      
            <asp:linkbutton id="Edit" text="Edit"
                    commandname="Edit" runat="server"/> 
            <asp:textbox id="FirstNameTextBox"
                    text='<%# Bind("FirstName") %>'
      
          </ItemTemplate>
      </asp:FormView>
      

      要访问控件及其值,例如

      TextBox firstNameTextBox = ((TextBox)FormView1.FindControl("FirstNameTextBox")).Text;
      
      string firstName = firstNameTextBox.Text;
      

      以下是帮助您前进的好文章


      希望对你有帮助

      【讨论】:

      • 感谢您的快速回答。但是,我确实将那部分放在了问题中,但由于它没有标记为代码,所以它把它去掉了。
      • 您是否在模板字段中放置了控件?
      猜你喜欢
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 2015-08-08
      • 2017-11-27
      • 1970-01-01
      相关资源
      最近更新 更多