Category Archives: DynamicControl

DynamicControl

[RESOLVED]Dynamic FormView

Hello,

Is it possible to add a dynamic formview to a placeholder, with edititemtemplate, insertitemtemplate, and itemtemplate’s created dynamically? and I wanted to load the data into that form view from a datatable, if possible? If so does anyone have a simple
example. I’ve been searching the web and haven’t found anything good, everythign that i have found, has been extremely complicated and not what i was looking for.

Any help is very much appreciated.

Thank you very much for your links, but that is alot more advanced than i expected, i’m looking for something a little bit simpler.

I am trying to figure it out,  and have came up with the following code:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class test3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable table = GetTable();
        FormView frm = new FormView();
        frm.ID = "FormView1";
        frm.DataSource = table;
        frm.DataBind();
        DynamicControlsHolder1.Controls.Add(frm);
    }

    static DataTable GetTable()
    {
        //
        // Here we create a DataTable with four columns.
        //
        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
        return table;
    }


}

But for some reason, it doesn’t dislpay anything. Can someone please help me with this?

Hi,

From what I understand you are having difficulty with generating FormView dynamically. According to your code, I find you have not created
ItemTemplate for FormView, that’s why your FormView not shown.

I have created a sample, please try to refer to the following code:

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace DynamicFormViewWeb

{

    public sealed class GenerTemplate : ITemplate

    {

        void ITemplate.InstantiateIn(Control container)

        {

            Label DosageLabel = new Label();

            DosageLabel.ID = "Dosage";

            DosageLabel.DataBinding += new EventHandler(DosageLabel_DataBinding);

             LiteralControl lineBreak = new LiteralControl("<br/>");

             Label DrugLabel = new Label();

             DrugLabel.ID = "Drug";

             DrugLabel.DataBinding += new EventHandler(DrugLabel_DataBinding);

             Label PatientLabel = new Label();

             PatientLabel.ID = "Patient";

             PatientLabel.DataBinding += new EventHandler(PatientLabel_DataBinding);

             Label DateLabel = new Label();

             DateLabel.ID = "Date";

             DateLabel.DataBinding += new EventHandler(DateLabel_DataBinding);

             //System.Web.UI.WebControls.LinkButton myBtn = new LinkButton();

             //myBtn.Text = "dd";

             //myBtn.ID = "Edit";

             //myBtn.CommandName = "Edit";

             container.Controls.Add(DosageLabel);

             container.Controls.Add(lineBreak);

             container.Controls.Add(DrugLabel);

             container.Controls.Add(lineBreak);

             container.Controls.Add(PatientLabel);

             container.Controls.Add(lineBreak);

             container.Controls.Add(DateLabel);

             //container.Controls.Add(myBtn);

         }

        private void DosageLabel_DataBinding(Object sender, EventArgs e)

        {

            Label DosageLabelControl = (Label)sender;

            FormView formViewContainer = (FormView)DosageLabelControl.NamingContainer;

            DataRowView rowView = (DataRowView)formViewContainer.DataItem;

            DosageLabelControl.Text = rowView["Dosage"].ToString();

        }

        private void DrugLabel_DataBinding(Object sender, EventArgs e)

        {

            Label DrugLabelControl = (Label)sender;

            FormView formViewContainer = (FormView)DrugLabelControl.NamingContainer;

            DataRowView rowView = (DataRowView)formViewContainer.DataItem;

            DrugLabelControl.Text = rowView["Drug"].ToString();

        }

        private void PatientLabel_DataBinding(Object sender, EventArgs e)

        {

            Label PatientLabelControl = (Label)sender;

            FormView formViewContainer = (FormView)PatientLabelControl.NamingContainer;

            DataRowView rowView = (DataRowView)formViewContainer.DataItem;

            PatientLabelControl.Text = rowView["Patient"].ToString();

        }

        private void DateLabel_DataBinding(Object sender, EventArgs e)

        {

            Label DateLabelControl = (Label)sender;

            FormView formViewContainer = (FormView)DateLabelControl.NamingContainer;

            DataRowView rowView = (DataRowView)formViewContainer.DataItem;

            DateLabelControl.Text = rowView["Date"].ToString();

        }

    }

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            DataTable table = GetTable();

            FormView frm = new FormView();

            frm.ID = "FormView2";

            frm.ItemTemplate = new GenerTemplate();

            frm.DataSource = table;

            frm.DataBind();

            form1.Controls.Add(frm);

        }

 

        static DataTable GetTable()

        {

            //

            // Here we create a DataTable with four columns.

            //

            DataTable table = new DataTable();

            table.Columns.Add("Dosage", typeof(int));

            table.Columns.Add("Drug", typeof(string));

            table.Columns.Add("Patient", typeof(string));

            table.Columns.Add("Date", typeof(DateTime));

 

            //

            // Here we add five DataRows.

            //

            table.Rows.Add(25, "Indocin", "David", DateTime.Now);

            table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);

            table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);

            table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);

            table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

            return table;

        }

    }

}

Hope it can help you, if you have any question, please let me know.

Best Regards,
Terry Guo

Wow, that was awesome, exactly what i was looking for, thank you!!!

[RESOLVED]Ajaxmodalpopup extender goes to new page instead of popping up window

I am trying to create a gridview inside a modalpopup extnder. But as soon as i click the button that triggers the event to create it, it seems to just act like a link to another page instead of popping up a window. Below is the code i have:

protected void Page_Load(object sender, EventArgs e)
    {
        DataTable table = GetTable();
        GridView gv = new GridView();
        gv.ID = "GridView1";
        gv.DataSource = table;
        gv.DataBind();

        Button btn = new Button();
        btn.ID = "button1";
        btn.Click += (sender, e) => CreateModalPop(ph, btn.ID);

        DynamicControlsHolder1.Controls.Add(gv);
        DynamicControlsHolder1.Controls.Add(btn);
    }


static DataTable GetTable()
    {
        //
        // Here we create a DataTable with four columns.
        //
        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
        return table;
    }


    protected void CreateModalPop(PlaceHolder ph, string btnID)
    {

        DataTable tableNew = GetTable();

        GridView gv = new GridView();
        gv.ID = "GridViewNew1"
        gv.AutoGenerateColumns = true;
        gv.DataSource = tableNew;
        gv.DataBind();


        Panel pn = new Panel();
        pn.ID = "Panel1";
        pn.Controls.Add(gv);


        AjaxControlToolkit.ModalPopupExtender modalPop = new AjaxControlToolkit.ModalPopupExtender();
        modalPop.ID = "ModalPopup-1";
        modalPop.PopupControlID = "Panel1"
        modalPop.TargetControlID = btnID;
        modalPop.X = 50;
        modalPop.Y = 50;
        modalPop.Show();

        // Adding modalpop to panel
        pn.Controls.Add(modalPop);

        // Adding Panel to placeholder
        ph.Controls.Add(pn);

    }

It’s just doing a postback.  If you put it inside of an updatepanel you won’t see the postback.

So i should try to put it inside of an updatepanel instead of regular panel?

You put you regular panel inside of the UpdatePanel.  The UpdatePanel just uses AJAX so you do not see the postback. 

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
    <asp:Panel ID="Panel1" runater="server">
      <!-- STUFF HERE -->
    </asp:Panel>
  </ContentTemplate>
</asp:UpdatePanel>

then if you want an ajax loader (in case it takes too long, you don’t get a response) download an ajax image loader here: http://www.ajaxload.info/

Then add this code where you want your loader to go.

<asp:UpdateProgress ID="updProg" AssociatedUpdatePanelID="upProfileEditEmail" DisplayAfter="500" runat="server">
  <ProgressTemplate>
    <img src="ajax-loader.gif" alt="Loading..." />
  </ProgressTemplate>
</asp:UpdateProgress>

I just modified the code and tried that, and get the same result. This thing is driving me crazy, i can’t figure out what i am doing wrong here.

protected void Page_Load(object sender, EventArgs e)
    {
        DataTable table = GetTable();
        GridView gv = new GridView();
        gv.ID = "GridView1";
        gv.DataSource = table;
        gv.DataBind();

        Button btn = new Button();
        btn.ID = "button1";
        btn.Click += (sender, e) => CreateModalPop(ph, btn.ID);

        DynamicControlsHolder1.Controls.Add(gv);
        DynamicControlsHolder1.Controls.Add(btn);
    }


static DataTable GetTable()
    {
        //
        // Here we create a DataTable with four columns.
        //
        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
        return table;
    }


    protected void CreateModalPop(PlaceHolder ph, string btnID)
    {

        DataTable tableNew = GetTable();

        GridView gv = new GridView();
        gv.ID = "GridViewNew1"
        gv.AutoGenerateColumns = true;
        gv.DataSource = tableNew;
        gv.DataBind();


        Panel pn = new Panel();
        pn.ID = "Panel1";
        pn.Controls.Add(gv);

		
		UpdatePanel up = new UpdatePanel();
		up.ID = "UpdatePanel1";
		up.ContentTemplateContainer.Controls.Add(pn);

        AjaxControlToolkit.ModalPopupExtender modalPop = new AjaxControlToolkit.ModalPopupExtender();
        modalPop.ID = "ModalPopup-1";
        modalPop.PopupControlID = "UpdatePanel1"
        modalPop.TargetControlID = btnID;
        modalPop.X = 50;
        modalPop.Y = 50;

        // Adding modalpop to panel
        pn.Controls.Add(modalPop);

        // Adding Panel to placeholder
        ph.Controls.Add(up);
        modalPop.Show();

 }

You aren’t setting a css class of your Panel (Panel1) or of the MPE (ModalPopup-1).  I think without that, it just has default values.  Here is an example I have:

set your Panel CssClass = "modalPopup" and your MPE CssClass = .modalBackground.  Then you can play around with it.

.modalBackground { background-color: Gray; filter: alpha(opacity=70); opacity: 0.7; cursor:not-allowed; position: absolute; top: 0%; left: 0%; width: 100%; height: 140%; overflow:hidden;}

.modalPopup { background-color: #ffffdd; border-width: 3px; border-style: solid; border-color: Gray; padding: 3px; width: 350px; }

[RESOLVED]CollapsiblePanelExtender causing FormatException

I have a web form containing a panel (collapsible) to allow me to add details of a "third party".
I also have a placeholder where at page_init, I loop through all persons saved, adding an instance of a user control (person) into this placeholder.

A "Save" button is available on the user control to allow updating the persons information.
If the user clicks this, the information is saved to the database,
HOWEVER the next post-back (be it navigation link, button click) causes the exception below

During the next post-back, page_init() executes (setting up of my custom usercontrols).  It gets as far as page_preload() and throws the exception. 
If I remove the collapsible panel there is no problem. 

any ideas?

ERROR
——–

String was not recognized as a valid Boolean.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid Boolean.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[FormatException: String was not recognized as a valid Boolean.]
System.Boolean.Parse(String value) +10757994
AjaxControlToolkit.CollapsiblePanelExtender.CollapsiblePanelExtender_ClientStateValuesLoaded(Object sender, EventArgs e) +164
AjaxControlToolkit.ExtenderControlBase.LoadClientStateValues() +290
AjaxControlToolkit.ExtenderControlBase.Page_PreLoad(Object sender, EventArgs e) +34
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Page.OnPreLoad(EventArgs e) +121
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +699

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18044

**************************** CODE:  ThirdParties.aspx ***********************************

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ThirdParties.aspx.cs" Inherits="ThirdParties" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%@ Register src="ThirdPartyUserControl.ascx" tagname="ThirdPartyUserControl" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<title>Third Parties</title>
</head>
<body>
<form id="form1" runat="server">

<div class = "container">
<div class="header">
<span style="float:left"> <asp:Label ID="lblClaim" runat="server" Text="Third Party details" CssClass="recordtitle1"></asp:Label> </span>
<span style="float:left"> <asp:Label ID="lblReadOnly" runat="server" Text="(Read Only)" CssClass="recordView" Visible="False"></asp:Label></span>

</div>
<div class="clear hideSkiplink">
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal" onmenuitemclick="NavigationMenu_MenuItemClick">
<Items>
<asp:MenuItem Text="Main Menu" Value="Main Menu"></asp:MenuItem>
<asp:MenuItem Text="Notification Summary" Value="Claim Summary"></asp:MenuItem>
<asp:MenuItem Text="Log Out" Value="Log Out"></asp:MenuItem>
</Items>
</asp:Menu>
</div>
<div class="clear hideSkiplink">
<asp:Menu ID="NavigationMenu2" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal" onmenuitemclick="NavigationMenu2_MenuItemClick">
<Items>
<asp:MenuItem Text="Details" Value="Details"></asp:MenuItem>
<asp:MenuItem Text="Vehicle & Driver" Value="Vehicle & Driver" Selected="true"></asp:MenuItem>
<asp:MenuItem Text="Third Parties" Value="Third Parties"></asp:MenuItem>
<asp:MenuItem Text="Witnesses" Value="Witnesses"></asp:MenuItem>
<asp:MenuItem Text="Audit Log" Value="Audit Log"></asp:MenuItem>
</Items>
</asp:Menu>
</div>

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div class="clear"></div> <br />

<asp:UpdatePanel ID="UpdatePanelAddTP" runat="server">
<ContentTemplate>
<asp:Panel ID="topPanel" runat="server" Width="300" CssClass="margin">
<asp:Label ID="lblInsert" runat="server" Text="Add third party" width="150" CssClass="headings"></asp:Label>
<asp:Image ID="imgToggle" runat="server" ImageUrl="~/Images/collapse.jpg" />
</asp:Panel>
<br />

<asp:Panel ID="bottomPanel" runat="server" CssClass="margin">
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label35" runat="server" Text="Third Party" style="font-weight: 700; margin-bottom:10px"></asp:Label> </span>
<span class="rowtext"> &nbsp;&nbsp;

<asp:TextBox ID="txtTPID" runat="server"
Enabled = "false" Width="60px" Visible="False"></asp:TextBox>&nbsp;
<asp:Label ID="Label8" runat="server"
Text="Notification ID" Visible="False"></asp:Label>&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="txtNotificationID" runat="server"
Enabled = "false" Width="60px" Visible="False"></asp:TextBox></span>
</div>
<br />
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label34" runat="server"
Text="Title"></asp:Label> </span>
<span class="rowtext">
<asp:DropDownList ID="dropTitle" CssClass="combo" Width="263px" runat="server" >
<asp:ListItem>Miss</asp:ListItem>
<asp:ListItem Selected="True">Mr</asp:ListItem>
<asp:ListItem>Mrs</asp:ListItem>
<asp:ListItem>Ms</asp:ListItem>
<asp:ListItem>Firm</asp:ListItem>
</asp:DropDownList>
</span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label36" runat="server"
Text="Name"></asp:Label> </span>

<span class="rowtext">
<asp:TextBox ID="txtTPName" runat="server"
CssClass="textbox" MaxLength="50"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidatorName"

runat="server" ControlToValidate="txtTPName"
ErrorMessage="Enter Name" CssClass="validationtext"
ValidationGroup="VG_TP">*</asp:RequiredFieldValidator>
</span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label4" runat="server" Text="Address Line 1"></asp:Label> </span>

<span class="rowtext"> <asp:TextBox ID="txtTPAddLine1" runat="server"
CssClass="textbox" MaxLength="50"></asp:TextBox> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label5" runat="server" Text="Address Line 2"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtTPAddLine2" runat="server"
CssClass="textbox" MaxLength="50"></asp:TextBox> </span>

</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label7" runat="server" Text="Town/City"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtTPTownCity" runat="server"
CssClass="textbox" MaxLength="50"></asp:TextBox> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label10" runat="server" Text="County"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtTPCounty" runat="server"
CssClass="textbox" MaxLength="50"></asp:TextBox> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label11" runat="server" Text="Postcode"></asp:Label> </span>
<span class="rowtext">
<asp:TextBox ID="txtTPPostcode" runat="server"
CssClass="textbox" MaxLength="20" Height="27px"></asp:TextBox> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label9" runat="server" Text="Country"></asp:Label> </span>
<span class="rowtext"> <asp:DropDownList ID="dropTPCountry" runat="server"
CssClass="combo" Width="263px" AppendDataBoundItems="True"
DataSourceID="SqlDataSourceCountries" DataTextField="Country"
DataValueField="Country">
<asp:ListItem Selected="True"></asp:ListItem>
</asp:DropDownList> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label1" runat="server" Text="Phone No"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtTPPhoneNo" runat="server"
CssClass="textbox" MaxLength="30"></asp:TextBox> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label2" runat="server" Text="Insurance Company"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtTPInsurer" runat="server" CssClass="textbox" MaxLength="30"></asp:TextBox> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label3" runat="server" Text="Policy No"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtTPPolicyNo" runat="server" CssClass="textbox" MaxLength="30"></asp:TextBox> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label6" runat="server" Text="Vehicle Registration No"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtRegNo" runat="server" CssClass="textbox" MaxLength="30"></asp:TextBox> </span>
</div>
<div class="row">
<span class="rowlabel"> <asp:Label ID="Label12" runat="server" Text="Vehicle Make"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtVehicleMake" runat="server" CssClass="textbox" MaxLength="50"></asp:TextBox> </span>
</div>

<div class="row">
<span class="rowlabel"> <asp:Label ID="Label13" runat="server" Text="Vehicle Model"></asp:Label> </span>
<span class="rowtext"> <asp:TextBox ID="txtVehicleModel" runat="server" CssClass="textbox" MaxLength="50"></asp:TextBox> </span>
</div>

<div class="row">
<asp:Button ID="cmdSaveTP" runat="server" Text="Save" CssClass="button"
ValidationGroup="VG_TP" onclick="cmdSaveTP_Click" /> 
</div>
<asp:ValidationSummary ID="ValidationSummary" runat="server" ValidationGroup="VG_TP" CssClass="validationtext" />

</div>
<br />

</asp:Panel>
<asp:CollapsiblePanelExtender ID="bottomPanel_CollapsiblePanelExtender"
runat="server" CollapseControlID="topPanel" Collapsed="True"
CollapsedImage="~/Images/expand.jpg" CollapsedText="Record Entry" Enabled="True"
ExpandControlID="topPanel" ExpandedImage="~/Images/collapse.jpg"
ExpandedText="Hide add third party" ImageControlID="imgToggle"
TargetControlID="bottomPanel" ExpandedSize="670">
</asp:CollapsiblePanelExtender>

</ContentTemplate>
</asp:UpdatePanel>

<div class="leftpanel">

<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<div class="userControl">
<asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>
</div>
</span>
</ContentTemplate>
</asp:UpdatePanel>
</div> <%–End of Left Panel –%>

<asp:SqlDataSource ID="SqlDataSourceCountries" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Country] FROM [Countries] ORDER BY [Country]"></asp:SqlDataSource>

<asp:RegularExpressionValidator ID="RegularExpressionValidatorPhone" runat="server" 
ControlToValidate="txtTPPhoneNo" Display="None" 
ErrorMessage="Phone No – Use numeric values without spaces" ValidationGroup="VG_TP"
ValidationExpression="d+"></asp:RegularExpressionValidator>

<asp:ObjectDataSource ID="ObjectDataSourceTPs" runat="server"
DataObjectTypeName="Project.A.BO.ThirdParty"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetList"
TypeName="Project.A.Bll.ThirdPartyManager" UpdateMethod="Save">
<SelectParameters> <asp:QueryStringParameter DefaultValue="" Name="notificationID" QueryStringField="ID" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</div> <%–End of Container–%>

<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>

****************** CODE EXTRACT:  ThirdParties.aspx.cs **********************

This method is called from page_init()…

private void TPAddDynamicControls()
{
ThirdPartyList tpList = ThirdPartyManager.GetList(Convert.ToInt32(Request.QueryString["ID"]));
ViewState["SessionID"] = Request.QueryString["SessionID"];
currSession.Load((String)ViewState["SessionID"]);

if (tpList != null)
{
int numOfTPs = tpList.Count();
int ControlID = 0;

for (int i = 0; i <= numOfTPs – 1; i++)

{
ThirdPartyUserControl DynamicUserControl = LoadControl("ThirdPartyUserControl.ascx") as ThirdPartyUserControl;
DynamicUserControl.ID = "uc" + ControlID;
((TextBox)DynamicUserControl.FindControl("txtTPID")).Text = Convert.ToString(tpList.ElementAt(i).iD);
((DropDownList)DynamicUserControl.FindControl("dropTitle")).Text = tpList.ElementAt(i).title;
((TextBox)DynamicUserControl.FindControl("txtTPName")).Text = tpList.ElementAt(i).name;
//more controls added here…

ph1.Controls.Add(DynamicUserControl);
ControlID += 1;

}
}

 

hi severn ,

From what I understand your issue is below:

Exception Details: System.FormatException: String was not recognized as a valid Boolean. 

You need to check for null (particularly Boolean e.g.) in your project.

Either don’t allow null in that column and use a default value, use select Is Null(CurrentMonthCollections, false) as CurrentMonthCollections for selecting a default value, or check for null before binding, you can do that inline via:

< %# ( Bind("CurrentMonthCollections") == DBNull.Value) ? false: true; %>

Please read the reference below for more information:

String was not recognized as a valid Boolean

 I hope it helps you.

[RESOLVED]Creating Persistent Dynamic Controls from Code Behind

I need to create a List of placeholder dynamically, In each placeholder there can be Label, texbox, gridview with template field, etc. The created controls and its values should be retained in postback.  What is the simplest way to get this. 

Thanks,

Bala

Hi,

I think the solution in
here
is what you are looking for as the following:

Yes, this is possible. One way to do this using purely ASP.NET (which seems like what you’re asking for) would be to keep a count of the TextBox

controls that you have added (storing that value in the ViewState) and recreate the TextBox
controls in the Page_Load event. Of course, nowadays most people would probably use Javascript or jQuery to handle this task client side, but I put together a quick example to demonstrate how it works with postbacks:

Front page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicControls.aspx.cs" Inherits="MyAspnetApp.DynamicControls" EnableViewState="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"></head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
        <asp:Button ID="btnWriteValues" runat="server" Text="Write" OnClick="btnWriteValues_Click" />
        <asp:PlaceHolder ID="phControls" runat="server" />
    </div>
    </form>
</body>
</html>

 

Code behind:

using System;
using System.Web.UI.WebControls;

namespace MyAspnetApp
{
    public partial class DynamicControls : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Recreate textbox controls
            if(Page.IsPostBack)
            {
                for (var i = 0; i < TextBoxCount; i++)
                    AddTextBox(i);
            }
        }

        private int TextBoxCount
        {
            get 
            {
                var count = ViewState["txtBoxCount"];
                return (count == null) ? 0 : (int) count;
            }
            set { ViewState["txtBoxCount"] = value; }
        }

        private void AddTextBox(int index)
        {
            var txt = new TextBox {ID = string.Concat("txtDynamic", index)};
            txt.Style.Add("display", "block");
            phControls.Controls.Add(txt);
        }

        protected void btnAddTextBox_Click(object sender, EventArgs e)
        {
            AddTextBox(TextBoxCount);
            TextBoxCount++;
        }

        protected void btnWriteValues_Click(object sender, EventArgs e)
        {
            foreach(var control in phControls.Controls)
            {
                var textBox = control as TextBox;
                if (textBox == null) continue;
                Response.Write(string.Concat(textBox.Text, "<br />"));
            }
        }
    }
}

 

Since you are recreating the controls on each postback, the values entered into the textboxes will be persisted across each postback. I added btnWriteValues_Click to quickly demonstrate how to read the values out of the textboxes.

EDIT
I updated the example to add a Panel containing a TextBox and a Remove Button. The trick here is that the Remove button does not delete the container Panel, it merely makes it not Visible. This is done so that all of the control IDs remain the same, so the data entered stays with each TextBox. If we were to remove the TextBox entirely, the data after the TextBox that was removed would shift down one TextBox on the next postback (just to explain this a little more clearly, if we have txt1, txt2 and txt3, and we remove txt2, on the next postback we’ll create two textboxes, txt1 and txt2, and the value that was in txt3 would be lost).

public partial class DynamicControls : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            for (var i = 0; i < TextBoxCount; i++)
                AddTextBox(i);
        }
    }

    protected void btnAddTextBox_Click(object sender, EventArgs e)
    {
        AddTextBox(TextBoxCount);
        TextBoxCount++;
    }

    protected void btnWriteValues_Click(object sender, EventArgs e)
    {
        foreach(var control in phControls.Controls)
        {
            var panel = control as Panel;
            if (panel == null || !panel.Visible) continue;
            foreach (var control2 in panel.Controls)
            {
                var textBox = control2 as TextBox;
                if (textBox == null) continue;
                Response.Write(string.Concat(textBox.Text, "<br />"));
            }
        }
    }

    private int TextBoxCount
    {
        get 
        {
            var count = ViewState["txtBoxCount"];
            return (count == null) ? 0 : (int) count;
        }
        set { ViewState["txtBoxCount"] = value; }
    }

    private void AddTextBox(int index)
    {
        var panel = new Panel();
        panel.Controls.Add(new TextBox {ID = string.Concat("txtDynamic", index)});
        var btn = new Button { Text="Remove" };
        btn.Click += btnRemove_Click;
        panel.Controls.Add(btn);
        phControls.Controls.Add(panel);
    }

    private void btnRemove_Click(object sender, EventArgs e)
    {
        var btnRemove = sender as Button;
        if (btnRemove == null) return;
        btnRemove.Parent.Visible = false;
    }
}

Best Regards.

[RESOLVED]How could send a label inside a panel as a DynamicContextKey?

i have ten blocks like this…and i put a label inside the panel_table_1 and panel_player_1 by codebehind…i want to send the text of label inside the panel_table_1 as DynamicContextKey.how should i do this?

<tr class="content" id="row1" onmouseover="$find('pce_1').showPopup();" onmouseout="$find('pce_1').hidePopup();">
<td class="style28">
    &nbsp;</td>
        <td class="style30">
            <asp:Panel ID="panel_player_1" runat="server">
            </asp:Panel>
        </td>
        <td class="style21" align="right">
            <asp:Panel ID="panel_table_1" runat="server" Width="50px">
            <ajaxToolkit:PopupControlExtender ID="PopupControlExtender1" runat="server" PopupControlID="Panel222" TargetControlID="panel_table_1"
               DynamicContextKey='<%# Eval("panel_table_1") %>' BehaviorID="pce_1"
               DynamicControlID="Panel222"
               DynamicServiceMethod="GetDynamicContent" Position="Bottom" OffsetX="-485" />
            </asp:Panel>
        </td>

</tr>

Hi xsidos,

Welcome to ASP.NET forums! I’m glad to see your active participation and discussion in ASP.NET forums.

I would like to suggest you check the following post to check the method using javascript to set value for DynamicContextKey

http://forums.asp.net/t/1436074.aspx

Hope this helps, thanks.

[RESOLVED]how to hide panel in modal popup extender if no record found

I am using modal popup extender where I want to hide pop up if there is no record.how to do that??

I tried  java script function

(‘ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "DeleteRedirect", "<script>hidediv();</script>", False)

,but that is not working in .I am using VB.Net.please help

<asp:GridView CssClass="forgrid" ID="GridView1" runat="server" AutoGenerateColumns="False" BorderColor="#336699"
BorderStyle="Solid" BorderWidth="1px" CellPadding="3" Font-Names="Verdana" Font-Size="10pt"

OnRowCreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="billId" HeaderText="Bill No" />
<asp:BoundField DataField="billAmount" HeaderText="Bill Amount" />
<asp:BoundField DataField="onDate" HeaderText="Date" />
<%–<asp:TemplateField ItemStyle-Width="40" ItemStyle-HorizontalAlign="Right"></asp:TemplateField> –%>
<asp:TemplateField ItemStyle-Width="40" HeaderText="Details" ItemStyle-HorizontalAlign="Right">
<ItemTemplate >
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/magnify.gif" />
<ajax:popupcontrolextender id="PopupControlExtender1" runat="server" popupcontrolid="Panel1"
targetcontrolid="Image1" dynamiccontextkey=’<%# Eval("billId") %>’ dynamiccontrolid="Panel1"
dynamicservicemethod="GetDynamicContent" OffsetY ="-200" OffsetX="-530" position="Top" >
</ajax:popupcontrolextender>
</ItemTemplate>
</asp:TemplateField>

</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" />
</asp:GridView>
</td> </tr>
</table>
<asp:Panel ID="Panel1" CssClass="panel11" BorderColor="#336699" BorderStyle="Solid" BorderWidth="3px" Height="300" ScrollBars="Vertical" runat="server" >
</asp:Panel>
</div>

<System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()> _
Public Shared Function GetDynamicContent(ByVal contextKey As String) As String
Dim pn As New Panel
Dim obj1 As New clsdatabase
Dim st As String = "select product_category.category,"
st += "product.heading,product_sale_detail.price,product_sale_detail.quantity"
st += " "
st += "from product_sale_detail,product_category,product "
st += "where product.proId = product_sale_detail.proId "
st += "and product.catId = product_category.catId"
st += " "
st += "and product_sale_detail.billId =" & contextKey
Dim query As String = "SELECT billId,quantity,price FROM product_sale_detail WHERE billId = " + contextKey
Dim table As New DataTable()
table = obj1.getDataTable(st)
Dim b As New StringBuilder()
Dim i As Integer
i = 0
If table.Rows.Count > 0 Then

b.Append("<table style=’background-color:#f3f3f3; border: #336699 0px solid; ")
b.Append("width:600px; font-size:10pt; font-family:Verdana;’ cellspacing=’0′ cellpadding=’4′>")
b.Append("<tr><td colspan=’3′ style=’ background-color:#336699; color:white;’>")
b.Append("<b>Details</b></td>")
b.Append("<td style=’ background-color:#336699; color:white; align:right’><a onclick=’hidediv();’ style=’cursor: pointer;’>Close</a>")
b.Append("</td></tr>")
b.Append("<tr><td style=’width:100px;’><b>Category</b></td>")
b.Append("<td style=’width:200px;’><b>Product Name</b></td>")
b.Append("<td style=’width:100px;’><b>Quantity</b></td>")
b.Append("<td style=’width:100px;’><b>Amount</b></td></tr>")
For Each row As DataRow In table.Rows
b.Append("<tr>")
b.Append("<td style=’width:100px;’ >" + table.Rows(i)("category").ToString() + "</td>")
b.Append("<td style=’width:200px;’>" + table.Rows(i)("heading").ToString() + "</td>")
b.Append("<td style=’width:100px;’>" + table.Rows(i)("quantity").ToString() + "</td>")
b.Append("<td style=’width:100px;’ >" + table.Rows(i)("price").ToString() + "</td>")
b.Append("</tr>")
i = i + 1
Next
b.Append("</table>")
Else
??????????????????????????????????????

End If

Return b.ToString()

End Function

try like this

<ajax:popupcontrolextender visible='<%# !IsDBNull(Eval("billId")) %>' ...

Hi,

To hide it with javascript, first assign a behaviorID to the extender. Then use the following code to close it.

function hide()
     {
         var bh = $find("pop");
         bh.hidePopup();
     }

         <ajaxToolkit:PopupControlExtender ID="PopupControlExtender1" BehaviorID="pop" runat="server" PopupControlID="Panel1" TargetControlID="Button1">
         </ajaxToolkit:PopupControlExtender

[RESOLVED]Find value of a dynamic control from a formview

I have created a dynamically created FromView which contains a list of user details.

<asp:Panel ID="DetailsPanel" runat="server" CssClass="formview">
<br />
<asp:FormView ID="FormView1" runat="server" DataSourceID="DetailsDataSource" RenderOuterTable="false"
OnPreRender="FormView1_PreRender" OnModeChanging="FormView1_ModeChanging" OnItemUpdated="FormView1_ItemUpdated"
OnItemInserted="FormView1_ItemInserted" OnItemDeleted="FormView1_ItemDeleted" OnItemCommand="FormView1_ItemCommand">
<HeaderTemplate>
<table id="detailsTable" class="DDDetailsTable" cellpadding="6" />
</HeaderTemplate>
<ItemTemplate>
<tr class="td">
<td class="DDLightHeader">Order No</td>
<td><asp:DynamicControl ID="OrderNo" runat="server" DataField="OrderNo" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">User ID</td>
<td><asp:DynamicControl runat="server" DataField="UserID" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Display Name</td>
<td><asp:DynamicControl runat="server" DataField="DisplayName" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Email Address</td>
<td><asp:DynamicControl ID="EmailAddress" runat="server" DataField="EmailAddress" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Project Code</td>
<td><asp:DynamicControl runat="server" DataField="ProjectCode" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Event Description</td>
<td><asp:DynamicControl runat="server" DataField="EventDesc" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Delivery Date</td>
<td><asp:DynamicControl runat="server" DataField="DeliveryDate" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Date Ordered</td>
<td><asp:DynamicControl runat="server" DataField="DateOrdered" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Site</td>
<td><asp:DynamicControl runat="server" DataField="Site" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time</td>
<td><asp:DynamicControl runat="server" DataField="Time" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time Room is Available</td>
<td><asp:DynamicControl ID="DynamicControl1" runat="server" DataField="TimeRoomAvailable" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time Room to be Cleared</td>
<td><asp:DynamicControl ID="DynamicControl2" runat="server" DataField="TimeCleared" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Location</td>
<td><asp:DynamicControl runat="server" DataField="Location" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Additional Information</td>
<td><asp:DynamicControl runat="server" ID="AdditionalInfo" DataField="AdditionalInfo" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Item Costs</td>
<td><asp:DynamicControl runat="server" ID="ItemCosts" DataField="ItemCosts" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">AdditionalCosts</td>
<td><asp:DynamicControl runat="server" ID="AdditionalCosts" DataField="AdditionalCosts" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Total Costs</td>
<td><asp:DynamicControl runat="server" DataField="TotalCosts" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">More Information Required</td>
<td><asp:DynamicControl runat="server" DataField="MoreInformationRequired" UIHint="MultilineText" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Reason Rejected</td>
<td><asp:DynamicControl runat="server" DataField="ReasonRejected" UIHint="MultilineText" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Order Progress</td>
<td><asp:DynamicControl runat="server" DataField="OrderProgress" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Imported Into Dream</td>
<td><asp:DynamicControl runat="server" DataField="ImportedIntoDream" /></td>
</tr>
<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit" Text="Edit" />
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete"
OnClientClick='return confirm("Are you sure you want to delete this item?");' />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr class="td">
<td class="DDLightHeader">Order No</td>
<td><asp:DynamicControl ID="OrderNo" runat="server" DataField="OrderNo" Mode="ReadOnly"/></td>
</tr>
<tr class="td">
<td class="DDLightHeader">User ID</td>
<td><asp:DynamicControl runat="server" DataField="UserID" Mode="ReadOnly"/></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Display Name</td>
<td><asp:DynamicControl runat="server" DataField="DisplayName" Mode="ReadOnly" /></td>

</tr>
<tr class="td">
<td class="DDLightHeader">Email Address</td>
<td><asp:DynamicControl runat="server" DataField="EmailAddress" ID="Email"/></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Project Code</td>
<td><asp:DynamicControl runat="server" DataField="ProjectCode" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Event Description</td>
<td><asp:DynamicControl runat="server" DataField="EventDesc" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Delivery Date</td>
<td><asp:DynamicControl runat="server" DataField="DeliveryDate" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Date Ordered</td>
<td><asp:DynamicControl runat="server" DataField="DateOrdered" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Site</td>
<td><asp:DynamicControl runat="server" DataField="Site" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time</td>
<td><asp:DynamicControl runat="server" DataField="Time" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time Room is Available</td>
<td><asp:DynamicControl ID="DynamicControl1" runat="server" DataField="TimeRoomAvailable" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time Room to be Cleared</td>
<td><asp:DynamicControl ID="DynamicControl2" runat="server" DataField="TimeCleared" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Location</td>
<td><asp:DynamicControl runat="server" DataField="Location" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Additional Information</td>
<td><asp:DynamicControl runat="server" DataField="AdditionalInfo" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Item Costs</td>
<td><asp:DynamicControl runat="server" ID="ItemCosts" DataField="ItemCosts" Mode="Edit" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Additional Costs</td>
<td><asp:DynamicControl runat="server" ID="AdditionalCosts" DataField="AdditionalCosts" Mode="Edit" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Total Costs</td>
<td><asp:DynamicControl runat="server" ID="TotalCosts" DataField="TotalCosts" Mode="Edit" /></td>
</tr>

<tr class="td">
<td class="DDLightHeader">More Information Required</td>
<td><asp:DynamicControl runat="server" DataField="MoreInformationRequired" Mode="Edit" UIHint="MultilineText" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Reason Rejected</td>
<td><asp:DynamicControl runat="server" DataField="ReasonRejected" Mode="Edit" UIHint="MultilineText" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Order Progress</td>
<td><asp:DynamicControl runat="server" DataField="OrderProgress" Mode="Edit" UIHint="OrderProgressDropDown" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Imported Into Dream</td>
<td><asp:DynamicControl runat="server" DataField="ImportedIntoDream" Mode="Edit" /></td>
</tr>

<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton4" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="LinkButton5" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />
</td>
</tr>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DynamicEntity ID="DynamicEntity3" runat="server" Mode="Insert" />
<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton6" runat="server" CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="LinkButton7" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />
</td>
</tr>
</InsertItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:FormView>

I’d like to be able to email the user, based on the email address in the formview, when I click update.

I have amended FormView1_Updated in the code behind as follows:

protected void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
{
string id = e.Keys["OrderNo"].ToString();


// I have tried this
//string email = FormView1.FindControl("EmailAddress").ToString();

//I have also tried this
//DynamicControl emailadd = ((DynamicControl)FormView1.FindControl("Email"));
//string email = emailadd.ToString();

GridView1.DataBind();
MailMessage objMail = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
objMail.To.Add(email);
objMail.From = new MailAddress("xxxx@xxxxxxx.xx.xx");
objMail.Subject = "Catering Request";
objMail.IsBodyHtml = true;
objMail.Body = "<html><body>" +
"<p><font face='Verdana' color='#000080' font size='2'>Your catering request, order number " + id + " has been updated by catering. Please view the " +
"<a href='http://dev-catering.bathspa.ac.uk/'>Catering Request System</a> for the details.</font></p>";

smtpClient.Port = xxxx;
smtpClient.Host = "xxxx.xxxxxxxxx.com";

NetworkCredential nc = new NetworkCredential("xxxxxx", "xxxxxxxxxxxxxxxx");
smtpClient.Credentials = nc;
smtpClient.Send(objMail);
}

If I type an email address straight into the objMail.To.Add(email) field this works fine. My problem is that I cannot capture the value of the email address in the FormView. I keep getting a null error. Has the value of the email address already been destroyed
before ‘ItemUpdated’ is called.

Or am I not finding the value am I just finding the control. If so how do I find the value of the dynamically created control.

Many thanks
Claire

The ID of the conrol that holds the email is different between the EditItemTemplate and the ItemTemplate. I suspect that when the Item_Updated event is raised by the FormView, the FormView will be showing it’s ItemTemplate, so you should look for the control
with ID= "EmailAddress" not "Email".

Also, regarding getting the value of the row key using this code that you wrote at the begging of the method:

string id = e.Keys["OrderNo"].ToString(); 

This will not work untill you set the FormView DataKeyNames proeprty to the name of the primiary key column as below:

<asp:FormView ID="…… "  DataKeyNames="OrderNo"</div> <div>After doing this, the e.Keys["OrderNo"] should return the correct value which you can use later on the query the database and
get the email address if you fail to get it from the FormView dynamic contorl.

Hi Anas

Thank you so much for this (and apologies for taking so long to reply. I had to work on something else).  I wasn’t sure which ID the Item_Updated event was using so that’s why they were different. I tried using "Email" and "EmailAddress" but I couldn’t get
either of these to work. However I did try your suggestion of using the orderID to query the database so this is what I have done for sending an email in the ItemUpdated event. Thank you so much (I was banging my head against the wall on this one).

However I’d also like to be able to send an email when the item is deleted (or deleting perhaps). I had added the code to send an email to the FormView1_ItemDeleted event but the row is deleted before the email is sent. So I tried to create a FormView1_ItemDeleting
event and add OnItemDeleting="FormView1_ItemDeleting" to the FormView1 source code ie

<asp:FormView ID="FormView1" runat="server" DataSourceID="DetailsDataSource" RenderOuterTable="false" DataKeyNames="OrderNo"
OnPreRender="FormView1_PreRender" OnModeChanging="FormView1_ModeChanging" OnItemUpdated="FormView1_ItemUpdated"
OnItemInserted="FormView1_ItemInserted" OnItemDeleted="FormView1_ItemDeleted" OnItemDeleting="FormView1_ItemDeleting"
OnItemCommand="FormView1_ItemCommand">

However when I run the project I am getting the error error CS0123: No overload for ‘FormView1_ItemDeleting’ matches delegate ‘System.Web.UI.WebControls.FormViewDeleteEventHandler’

Do you have any idea how I can add my code to send an email when deleting a row?

Many thanks
Claire 

coxy16

However when I run the project I am getting the error error CS0123: No overload for ‘FormView1_ItemDeleting’ matches delegate ‘System.Web.UI.WebControls.FormViewDeleteEventHandler’

Make sure you have the following signature for the "FormView1_ItemDeleting" function (check in code behind):

protected void FormView1_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {

        }

Thank you again Anas. I should have mentioned that I tried this. I have added OnItemDeleting="FormView1_ITemDeleting" to the source code ie

<asp:FormView ID="FormView1" runat="server" DataSourceID="DetailsDataSource"
                    RenderOuterTable="false" DataKeyNames="OrderNo"
                    OnPreRender="FormView1_PreRender" OnModeChanging="FormView1_ModeChanging" OnItemUpdated="FormView1_ItemUpdated"
                    OnItemInserted="FormView1_ItemInserted"
                    OnItemDeleted="FormView1_ItemDeleted" OnItemCommand="FormView1_ItemCommand" OnItemDeleting="FormView1_ItemDeleting">

And in the code behind I have added 

protected void FormView1_ItemDeleting(object sender, FormViewDeletedEventArgs e)
        {
            string orderNo = e.Keys["OrderNo"].ToString();
            using (SqlConnection orderConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cateringConnectionString"].ConnectionString))
            {
                SqlCommand orderCommand = orderConnection.CreateCommand();
                orderConnection.Open();

                orderCommand.CommandText = "SELECT EmailAddress FROM tblCatering WHERE OrderNo = " + orderNo;
                SqlDataReader readerOrder = orderCommand.ExecuteReader();
                if (readerOrder.Read())
                {
                    string emailAddress = readerOrder["EmailAddress"].ToString();
                    readerOrder.Close();

                    GridView1.DataBind();
                    MailMessage objMail = new MailMessage();
                    SmtpClient smtpClient = new SmtpClient();
                    objMail.To.Add(emailAddress);
                    objMail.From = new MailAddress("catering@xxxxxxxxx.xx.xx");
                    objMail.Subject = "Catering Request";
                    objMail.IsBodyHtml = true;
                    objMail.Body = "<html><body>" +
                                "<p><font face='Verdana' color='#000080' font size='2'>Your catering request, order number " + orderNo + ", has been updated by catering. Please view the " +
                                "<a href='http://dev-catering.bathspa.ac.uk/'>Catering Request System</a> for the details.</font></p>";

                    smtpClient.Port = xxxx;
                    smtpClient.Host = "xxxx.xxxxxxx.xxx";

                    NetworkCredential nc = new NetworkCredential("xxxxxxx", "xxxxxxxxxxxxxx");
                    //SmtpClient smtpClient = new SmtpClient("xxxxxxxxx.xxxxxxxx.xx.xx");
                    smtpClient.Credentials = nc;
                    smtpClient.Send(objMail);
                }
            }
        }

However I am getting this error

No overload for ‘FormView1_ItemDeleting’ matches delegate ‘System.Web.UI.WebControls.FormViewDeleteEventHandler’

Is there another reference I need to add somewhere?

Thanks for all your help with this.

coxy16

protected void FormView1_ItemDeleting(object sender, FormViewDeletedEventArgs e)

The singnature is not valid. You are using FormViewDeletedEventArgs and you should use “FormViewDeleteEventArgs” (without the “d”) , please refer to the sample i posted in my previous reply. So we have two different event arguments one for Item deleted and another one for ItemDeleting. 

For ItemDeleting: use FormViewDeleteEventArgs

e.g.

 protected void FormView1_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
 
        }

For ItemDeleted: use FormViewDeletedEventArgs

e.g.

protected void FormView1_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
 
        }

Thank you, thank you, thank you. I’m so sorry I didn’t spot that. You are a total star. Smile

That has worked. Brilliant. Thanks again for your help.

[RESOLVED](mvc-ish) editor templates

Is it achievable in asp.net web forms .net 4.0 ( vs2k10 ) ? Perhaps asp:DynamicControl ? I basically want to have one place manage all "types" of inputs e.g. for date inputs, phone inputs, numeric inputs etc.

Hi,

For this situation, asp:DynamicControl displays the content that is defined for the field in templated data-bound controls, using ASP.NET Dynamic Data features. And now you want to  find some editor templates for date inputs, phone inputs, numeric inputs
etc. You may refer to the following links for more information:

http://msdn.microsoft.com/en-us/library/system.web.dynamicdata.dynamiccontrol(v=vs.110).aspx 

http://blogs.telerik.com/kendoui/posts/13-10-29/diving-into-asp.net-mvc-templates

If I misunderstand, you could describe the issue in detail so that we could figure it out.

[RESOLVED]usercontrol Paging Issue

Hi Gurus,

  I am dynamically calling a usercontrol,

 I am not using any database code in it. if u simply copy and paste.it will work from your end as well.

 I pasted my code below.

My issue:

when i click on the linkbutton, the user control is loading, but when the paging is clicked inside usercontrol, then the usercontrol is hiding.
Please help me out with this.

 (i need to use custom paging not built in paging)

Here is the code:

Default.aspx

——————

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DynamicControls._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="Sc1" runat="server">
</asp:ScriptManager>
<table>
<tr>
<td>
<asp:LinkButton ID="lnk1" runat="server" Text="Control1" CommandName="Control1" OnCommand="lnk1_Click"></asp:LinkButton>
<br />
<asp:LinkButton ID="lnk2" runat="server" Text="Control2" CommandName="Control2" OnCommand="lnk1_Click"></asp:LinkButton>
<br />
<asp:LinkButton ID="lnk3" runat="server" Text="Control3" CommandName="Control3" OnCommand="lnk1_Click"></asp:LinkButton>
</td>
<td>
<asp:Panel ID="pnl1" runat="server" Visible="false">
This is Control1
</asp:Panel>
<asp:Panel ID="pnl2" runat="server" Visible="false">
This is Control2
</asp:Panel>
<asp:Panel ID="pnl3" runat="server" Visible="false">
</asp:Panel>
</td>
</tr>
</table>
</asp:Content>

Default.aspx.cs

—————-

protected void lnk1_Click(object sender, CommandEventArgs e)
{
if (e.CommandName == "Control1")
{
//e.Tab.Selected = true;
pnl1.Visible = true;
pnl2.Visible = false;
pnl3.Visible = false;
}
if (e.CommandName == "Control2")
{
pnl1.Visible = false;
pnl2.Visible = true;
pnl3.Visible = false;
}
if (e.CommandName == "Control3")
{

pnl3.Controls.Clear();
string controlPath = "~/Controls/RadSchedulerCS.ascx";
RadSchedulerCS uc = (RadSchedulerCS)LoadControl(controlPath);
uc.ID = "RadScheduler";
uc.BindGrid(1);
pnl3.Controls.Add(uc);

pnl1.Visible = false;
pnl2.Visible = false;
pnl3.Visible = true;

}

}

protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
{

pnl3.Controls.Clear();
string controlPath = "~/Controls/RadSchedulerCS.ascx";
RadSchedulerCS uc = (RadSchedulerCS)LoadControl(controlPath);
uc.ID = "RadScheduler";
uc.BindGrid(1);
pnl3.Controls.Add(uc);

}

RadSchedulerCS.ascx

—————————

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RadSchedulerCS.ascx.cs" Inherits="DynamicControls.Controls.RadSchedulerCS" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>

<asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text=’<%#Eval("ID") %>’ Visible="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text=’<%# Eval("FName") %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="DOB">
<ItemTemplate>
<asp:Label ID="lblDOB" runat="server" Text=’<%# Eval("DOB") %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>
<asp:DataList CellPadding="5" RepeatDirection="Horizontal" runat="server" ID="dlPager"
OnItemCommand="dlPager_ItemCommand" >
<ItemTemplate>
<asp:LinkButton Enabled=’<%#Eval("Enabled") %>’ runat="server" ID="lnkPageNo" Text=’<%#Eval("Text") %>’
CommandArgument=’<%#Eval("Value") %>’ CommandName="PageNo" CausesValidation="false"></asp:LinkButton>
</ItemTemplate>
</asp:DataList>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DynamicControls.Controls
{
public partial class RadSchedulerCS : System.Web.UI.UserControl
{
#region DECLRATIONS
public delegate void MyCustomHandler(object sender, EventArgs e); //This is for button click
public event MyCustomHandler SomethingClicked;

#endregion

protected void Page_PreRender(object sender, EventArgs e)
{
// Workaround to prevent clicking twice on the pager to have results displayed properly
this.Gv1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid(1);
}
}
public void BindGrid(int currentPage)
{
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { ID = 1, FName = "John", DOB = DateTime.Parse("12/11/1971") });
empList.Add(new Employee() { ID = 2, FName = "Mary", DOB = DateTime.Parse("01/17/1961") });
empList.Add(new Employee() { ID = 3, FName = "Amber", DOB = DateTime.Parse("12/23/1971") });
empList.Add(new Employee() { ID = 4, FName = "Kathy", DOB = DateTime.Parse("11/15/1976") });
empList.Add(new Employee() { ID = 5, FName = "Lena", DOB = DateTime.Parse("05/11/1978") });
empList.Add(new Employee() { ID = 6, FName = "John1", DOB = DateTime.Parse("12/11/1971") });
empList.Add(new Employee() { ID = 7, FName = "Mary1", DOB = DateTime.Parse("01/17/1961") });
empList.Add(new Employee() { ID = 8, FName = "Amber1", DOB = DateTime.Parse("12/23/1971") });
empList.Add(new Employee() { ID = 9, FName = "Kathy1", DOB = DateTime.Parse("11/15/1976") });
empList.Add(new Employee() { ID = 10, FName = "Lena1", DOB = DateTime.Parse("05/11/1978") });
empList.Add(new Employee() { ID = 11, FName = "John2", DOB = DateTime.Parse("12/11/1971") });

int TotalCount = empList.Count();

var pgNo = currentPage;
var pgRec = 10;
empList = empList.Skip((pgNo – 1) * pgRec).Take(pgRec).ToList();
Gv1.DataSource = empList;
Gv1.DataBind();
generatePager(TotalCount, pgRec, pgNo);
}

public void generatePager(int totalRowCount, int pageSize, int currentPage)
{
int totalLinkInPage = 3;
int totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);
int startPageLink = Math.Max(currentPage – (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
int lastPageLink = Math.Min(startPageLink + totalLinkInPage – 1, totalPageCount);
if ((startPageLink + totalLinkInPage – 1) > totalPageCount)
{
lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
startPageLink = Math.Max(lastPageLink – totalLinkInPage + 1, 1);
}
List<ListItem> pageLinkContainer = new List<ListItem>();

if (startPageLink != 1)
{
int prevcounts = currentPage – 1;
pageLinkContainer.Add(new ListItem("First", prevcounts.ToString(), currentPage != 1));
}
for (int i = startPageLink; i <= lastPageLink; i++)
{
pageLinkContainer.Add(new ListItem(i.ToString(), i.ToString(), currentPage != i));
}
if (lastPageLink != totalPageCount)
{
int Nextcounts = currentPage + 1;
pageLinkContainer.Add(new ListItem("Last", Nextcounts.ToString(), currentPage != totalPageCount));
}

dlPager.DataSource = pageLinkContainer;
dlPager.DataBind();
}
protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
{

if (SomethingClicked != null)
{
SomethingClicked(source, e);
if (e.CommandName == "PageNo")
{
BindGrid(Convert.ToInt32(e.CommandArgument));
}
}

}
class Employee
{
public int ID { get; set; }
public string FName { get; set; }
public DateTime DOB { get; set; }
}

}
}

I need it urgent,how to accomplish this,is any possibilities by using Delegates or any wayz,if so how to do that.

Help me with this.

Thanks in Advance

Hi,

So far as I know, if we have dynamically loaded the user control, after we click the paging of the user control, we should reload it again. Because it will do pastback after you click the Paging.

Also we can add the User control into a Place Holder control, then we did not need to reload again.

There are some information about dynamically load user control and custom paging user control, please refer to the links below:

http://www.codeproject.com/Articles/6448/Custom-Paging-with-User-Control

http://www.codeproject.com/Articles/59781/Dynamic-Loading-of-ASP-NET-User-Controls

Hope it’s useful for you.

Best Regards,

Michelle Ge

[RESOLVED]Display other fields in details view based on drop down list

I have a details view where I have converted the AgentName field to a template and added a dropdown box.  Now I need to know how to display the email address of the selected agent name. 

Private Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting
        Dim fFileAttachment As FileUpload = CType(Me.DetailsView1.FindControl("FileUploadFileAttachment"), FileUpload)
        e.Values("PhotoPath") = "../images/" + fFileAttachment.FileName
        Dim DLAgentName As DropDownList = CType(Me.DetailsView1.FindControl("DLAgentName"), DropDownList)
        e.Values("AgentName") = DLAgentName.SelectedItem.Value
        Dim LblEmail As Label = CType(Me.DetailsView1.FindControl("LblEmail"), Label)
        e.Values("email") = LblEmail
        If fFileAttachment.HasFile Then
            Dim path As String = Server.MapPath("../images/" + fFileAttachment.FileName)
            ' grant Write permission to the ASP.NET process account
            ' for the Images subdirectory.
            fFileAttachment.SaveAs(path)

        End If
    End Sub

What version of .NET are you on? In the newer versions you should be able to do the binding in markup so you don’t have to look up values and put them in e.Values. (With the exception of PhotoPath.)

Not entirely sure what you mean by "display the email address of the selected agent name". You are only showing the ItemInserting. That isn’t for display. Do you mean you want to have the selected record in the DetailsView follow the selection in theDropDownList?

If so, you have a Master/Details setup. You may want to search the web for examples. Usually in such setups, the master is outside the details. (In this case, the DropDownList is outside the DetailsView.) That will prevent interference in databinding between
the Controls.

Basics: Set AutoPostBack = true on the DropDownList. Handle its SelectedIndexChanged event. In the handler, get the selected value and use it to bind the DetailsView to the right record.

From Superguppie:  "Not entirely sure what you mean by "display the email address of the selected agent name". You are only showing the ItemInserting. That isn’t for display. Do you mean you want to have the selected record in the DetailsView follow
the selection in theDropDownList?"  Yes
 I want to be able to display the values that are associated with the agent or person name that I select in the dropdown list appropriate ItemInserting areas. One of the fields I want to insert based on called email.   My drop down list
is a look up from another sql connection to the agent name.  

<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="739px"
         AllowPaging="True" AutoGenerateRows="False" BackColor="White"
         BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
         DataKeyNames="PID" DataSourceID="SqlDataSource1" DefaultMode="Insert"
         GridLines="Horizontal" HorizontalAlign="Center">
        <EditRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
        <Fields>
            <asp:BoundField DataField="PID" HeaderText="PID" InsertVisible="False"
                ReadOnly="True" SortExpression="PID" />
            <asp:BoundField DataField="PAddress" HeaderText="Property Address"
                SortExpression="PAddress" />
            <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            <asp:BoundField DataField="St" HeaderText="St" SortExpression="St" />
            <asp:BoundField DataField="Zip" HeaderText="Zip" SortExpression="Zip" />
            <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
            <asp:BoundField DataField="Beds" HeaderText="Beds" SortExpression="Beds" />
            <asp:BoundField DataField="Bath" HeaderText="Bath" SortExpression="Bath" />
            <asp:BoundField DataField="SqFt" HeaderText="SqFt" SortExpression="SqFt" />
            <asp:BoundField DataField="MLS" HeaderText="MLS" SortExpression="MLS" />
            <asp:BoundField DataField="Description" HeaderText="Description"
                SortExpression="Description" />
            <asp:TemplateField HeaderText="Agent Name" SortExpression="AgentName">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("AgentName") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:DropDownList ID="DLAgentName" runat="server" DataSourceID="SqlDataSource2" DataTextField="AgentName" DataValueField="AgentName" Height="18px" Width="286px">
                    </asp:DropDownList>
                    <asp:HyperLink ID="HLManageAgents" runat="server" NavigateUrl="~/Admin/Default.aspx" Target="_blank">Manage Agents</asp:HyperLink>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("AgentName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Agent Email" SortExpression="AgentEmail">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("AgentEmail") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="txtboxagentemail" runat="server"></asp:TextBox>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("AgentEmail") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="Status" HeaderText="Status"
                SortExpression="Status" />
            <asp:TemplateField ConvertEmptyStringToNull="False" HeaderText="Photo" SortExpression="PhotoPath">
                <EditItemTemplate>
                    <asp:DynamicControl ID="DynamicControl1" runat="server" DataField="PhotoPath" Mode="Edit" />
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:FileUpload ID="FileUploadFileAttachment" FileName='<%# Bind("PhotoPath") %>'   runat="server" />
                    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:DynamicControl ID="DynamicControl1" runat="server" DataField="PhotoPath" Mode="ReadOnly" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowDeleteButton="True" ShowEditButton="True"
                ShowInsertButton="True" />
        </Fields>
        <FooterStyle BackColor="White" ForeColor="#333333" />
        <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="White" ForeColor="#333333" />
    </asp:DetailsView>
 Private Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting
        Dim fFileAttachment As FileUpload = CType(Me.DetailsView1.FindControl("FileUploadFileAttachment"), FileUpload)
        e.Values("PhotoPath") = "../images/" + fFileAttachment.FileName
        Dim DLAgentName As DropDownList = CType(Me.DetailsView1.FindControl("DLAgentName"), DropDownList)
        e.Values("AgentName") = DLAgentName.SelectedItem.Value
        Dim LblEmail As Label = CType(Me.DetailsView1.FindControl("LblEmail"), Label)
        e.Values("email") = DLAgentName
        If fFileAttachment.HasFile Then
            Dim path As String = Server.MapPath("../images/" + fFileAttachment.FileName)
            ' grant Write permission to the ASP.NET process account 
            ' for the Images subdirectory. 
            fFileAttachment.SaveAs(path)

        End If
    End Sub

If I get this right, you want to lookup data as the selection is made from the DropDownList. Then use the data to fill the Controls in the InsertItemTemplate. These can then later be inserted from these Controls in the regular way.

If that is correct, set AutoPostBack = true on the DropDownList and handle its SelectedIndexChanged.

The sender object is the DropDownList. So if you cast to that, you can get the SelectedValue. Then use that to look up the Agent.

The NamingContainer of the DropDownList is the DetailsView. You can use FindControl to find the Controls that need their value set. Then you can set the values.

You can use Bind on the Text properties of the Controls, just like you did in the EditItemTemplate. DetailsView will do the extraction for you when you click Insert.

I updated the code below so that it would show the email based on the agentname I selected and it doesn’t show anything.  Any ideas on what I am missing?

Private Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting
        Dim fFileAttachment As FileUpload = CType(Me.DetailsView1.FindControl("FileUploadFileAttachment"), FileUpload)
        e.Values("PhotoPath") = "../images/" + fFileAttachment.FileName
        Dim DLAgentName As DropDownList = CType(Me.DetailsView1.FindControl("DLAgentName"), DropDownList)
        e.Values("AgentName") = DLAgentName.SelectedItem.Value
        Dim txtboxAgentEmail As TextBox = CType(Me.DetailsView1.FindControl("txtboxAgentEmail"), TextBox)
        e.Values("Agentemail") = txtboxAgentEmail
        If fFileAttachment.HasFile Then
            Dim path As String = Server.MapPath("../images/" + fFileAttachment.FileName)
            ' grant Write permission to the ASP.NET process account
            ' for the Images subdirectory.
            fFileAttachment.SaveAs(path)

        End If
    End Sub

Dim txtboxAgentEmail As TextBox = CType(Me.DetailsView1.FindControl("txtboxAgentEmail"), TextBox)
        e.Values("Agentemail") = DLAgentName.SelectedValue

With this piece of code above I get the Agent Name listed in the DLAgentName field to post into the agentemail column.  What am I missing to get the Agentemail associated with the agent name I selected in the drop down list?

Well, in the .aspx you posted, I don’t see DetailsView1_ItemInserting being hooked up to the DetailsView. So my guess is, the code is never executed.

Also, ItemInserting is executed when the Insert is about to take place. If you want to show data as soon as a value is selected in the DropDownList, you should handle the SelectedIndexChanged of the DropDownList (and set AutoPostBack = true on that)