views:

244

answers:

3

I have a simple form. Let's say one textbox and a button.

If these items are placed on the aspx page, they are automatically added to the *.designer.cs file and they can be referenced in my C# code behind. Just like it's supposed to.

The problem occurrs when I take these items and place them within an for a FormView control. At that point all traces of them are removed from the designer.cs file and any code written using these controls now give "does not exist in current context" error. The FormView control itself is left in the designer code behind. If I re-add them they won't stick. If I delete the designer.cs and let it remake, it just remakes without the controls.

Any clues?

A: 

If you want to add controls to a FormView, Use ItemTemplate, and drop the desired controls onto itemTemplate. Then you can access those controls from code behind.

here is a sample

<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>

To access a control and it's value, some thing like

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

string firstName = firstNameTextBox.Text;

Following is good article to get you going


Hope this helps

Asad Butt
Thanks for the quick answer. However, I did put that part in the question but it took it out since it wasn't marked as code.
Anthony
have you put controls inside Template Fields?
Asad Butt
A: 

I figured it out by searching for answers a little differently. You have to use FindControl since the items are in the FormView control. See example:

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

Anthony
A: 

Another approach for this, if you're only dealing with 1 EditItemTemplate (or whichever template) is to inherit from FormView and override setting the TemplateInstance attribute to TemplateInstance.Single. Like this:

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; }
  }
}

If you use that FormView control in your page, the controls in the EditItemTemplate will appear in your designer, and be directly accessible in the code-behind as well.

Nick Craver