473,698 Members | 2,631 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

InsertItemTempl ate and ControlParamete r

I have a simple Formview like this:

<%@ Page Language="C#" EnableViewState ="true" AutoEventWireup ="true"
CodeFile="Hello World.aspx.cs" Inherits="_Hell oWorld"%>

<html>
<body>
<form runat="server">
<asp:FormView DataSourceID="m yODS"
ID="ItemFormVie w"
runat="server">
<InsertItemTemp late>
<asp:DropDownLi st ID="myDDL" runat="server"> </
asp:DropDownLis t>
</InsertItemTempl ate>
</asp:FormView>

<asp:ObjectData Source ID="myODS" runat="server" >
<SelectParamete rs>
<asp:ControlPar ameter ControlID="faa" />
</SelectParameter s>
</asp:ObjectDataS ource>

<asp:TextBox ID="faa" runat="server" visible="false" ></
asp:TextBox>
</form>

</body>
</html>

and a codebehind file

using System;
using System.Data;
using System.Configur ation;
using System.Web;
using System.Web.Secu rity;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;

public partial class _HelloWorld : System.Web.UI.P age
{

protected void Page_Load(objec t sender, EventArgs e)
{
ItemFormView.Ch angeMode(FormVi ewMode.Insert);
if (!IsPostBack)
PopulateDDL();
}

private void PopulateDDL()
{
DropDownList ddl =
(DropDownList)I temFormView.Fin dControl("myDDL ");

ddl.Items.Add(" aaa");
ddl.Items.Add(" bbb");
ddl.Items.Add(" ccc");
}

}
When I run this page, the dropdown list is expected to be populated,
but it's not. However, if I remove the line

<asp:ControlPar ameter ControlID="faa" />

, it then works. It also works perfectly if using other type of
parameter, like

<asp:Paramete r Name="woo"/>

So, I don't understand what happen behind the scene. Any idea???

Thanks in advance!

Nate

Feb 2 '07 #1
2 5694
Hi there,

I had a look at the System.Web.UI.W ebControls code, and it seems there’s a
tiny *bug* - ConvertEmptyStr ingToNull is not used in
ControlParamete r.Evaluate() method. Let me explain the problem in details.
Every Parameter in ObjectDataSourc e.SelectParamet ers collection inherits from
System.Web.UI.W ebControls.Para meter class, which defines virtual method
protected virtual object Evaluate(HttpCo ntext context, Control control)
{
Return null;
}
As you can see default implementation returns null reference, but every
derived parameter class overrides this method with its own implementation
(this mechanism is called polymorphism). For instance, ControlParamete r class
provides its own, following implementation:

protected override object Evaluate(HttpCo ntext context, Control control)
{
if (control == null)
{
return null;
}
string text1 = this.ControlID;
string text2 = this.PropertyNa me;
if (text1.Length == 0)
{
throw new
ArgumentExcepti on(SR.GetString ("ControlParame ter_ControlIDNo tSpecified", new
object[] { base.Name }));
}
Control control1 = DataBoundContro lHelper.FindCon trol(control, text1);
if (control1 == null)
{
throw new
InvalidOperatio nException(SR.G etString("Contr olParameter_Cou ldNotFindContro l", new object[] { text1, base.Name }));
}
ControlValuePro pertyAttribute attribute1 =
(ControlValuePr opertyAttribute )
TypeDescriptor. GetAttributes(c ontrol1)[typeof(ControlV aluePropertyAtt ribute)];
if (text2.Length == 0)
{
if ((attribute1 == null) || string.IsNullOr Empty(attribute 1.Name))
{
throw new
InvalidOperatio nException(SR.G etString("Contr olParameter_Pro pertyNameNotSpe cified", new object[] { text1, base.Name }));
}
text2 = attribute1.Name ;
}
object obj1 = DataBinder.Eval (control1, text2);
if (((attribute1 != null) && string.Equals(a ttribute1.Name, text2,
StringCompariso n.OrdinalIgnore Case)) && ((attribute1.De faultValue != null) &&
attribute1.Defa ultValue.Equals (obj1)))
{
return null;
}
return obj1;
}

A lot of code but nothing really interesting – the only thing missing is use
of ConvertEmptyStr ingToNull. However, the problem shows up somwehere else -
in ParameterCollec tion class. As you may know every BaseDataBoundCo ntrol
(including FormView) populates the data on prerender event. Before doing so,
control performs a simple check to see if the data needs to be (re)populated
(actually this task is delegated to SelectParameter s member which is an
instance of ParameterCollec tion class, control is notified by handling
ParametersChang ed event which occurrence indicates data should be retrieved
again):

public void ParameterCollec tion.UpdateValu es(HttpContext context, Control
control)
{
foreach (Parameter parameter1 in base)
{
parameter1.Upda teValue(context , control);
}
}

And here comes the problem:

internal void Parameter.Updat eValue(HttpCont ext context, Control control)
{
object originalValue = this.ViewState["ParameterValue "];
object evaluatedValue = this.Evaluate(c ontext, control);
this.ViewState["ParameterValue "] = obj2;
if (((evaluatedVal ue == null) && (originalValue! = null)) ||
((evaluatedValu e!= null) && ! evaluatedValue. Equals(original Value)))
{
this.OnParamete rChanged();
}
}

In your case, originalValue is null, evaluatedValue is String.Empty
therefore parameter is considered as changed (TextBox.Text never returns null
reference but String.Empty, unfortunately, as I mentioned,
ControlPatamete r.Eval() method does not replace empty string with null value
even if ConvertEmptyStr ingToNull == true. It doesn’t happen for Parameter
class because Parameter.Eval( ) always returns null, so the condition
if (((evaluatedVal ue == null) && (originalValue! = null)) ||
((evaluatedValu e!= null) && ! evaluatedValue. Equals(original Value)))
{
this.OnParamete rChanged();
}
is never met.

There are two easy ways to solve the problem.
1. Do not use Page_Load event to popuate the dropdownlist, use pre_render:

protected void Page_PreRender( object sender, EventArgs e)
{
if (!IsPostBack)
PopulateDDL();
}

2. Create your own parameter class derived from ControlParamete r

public class MyControlParame ter : ControlParamete r
{

protected override void LoadViewState(o bject savedState)
{
base.LoadViewSt ate(savedState) ;
}

protected override object Evaluate(HttpCo ntext context, Control control)
{
object value = base.Evaluate(c ontext, control);

if (value is String)
{
if (ConvertEmptySt ringToNull && ((string)value) == String.Empty)
return null;
else
return value;
}
else
return value;
}
}
<asp:FormView ID="ItemFormVie w" DataSourceID="m yODS" runat="server"
DefaultMode="In sert">
<InsertItemTemp late>
<asp:DropDownLi st ID="myDDL" runat="server"/>
</InsertItemTempl ate>
</asp:FormView>

<asp:ObjectData Source ID="myODS" runat="server">
<SelectParamete rs>
<cc1:MyControlP arameter ControlID="faa" PropertyName="T ext"/>
</SelectParameter s>
</asp:ObjectDataS ource>

<asp:TextBox ID="faa" runat="server" visible="true"/>
--
Milosz

"np****@gmail.c om" wrote:
I have a simple Formview like this:

<%@ Page Language="C#" EnableViewState ="true" AutoEventWireup ="true"
CodeFile="Hello World.aspx.cs" Inherits="_Hell oWorld"%>

<html>
<body>
<form runat="server">
<asp:FormView DataSourceID="m yODS"
ID="ItemFormVie w"
runat="server">
<InsertItemTemp late>
<asp:DropDownLi st ID="myDDL" runat="server"> </
asp:DropDownLis t>
</InsertItemTempl ate>
</asp:FormView>

<asp:ObjectData Source ID="myODS" runat="server" >
<SelectParamete rs>
<asp:ControlPar ameter ControlID="faa" />
</SelectParameter s>
</asp:ObjectDataS ource>

<asp:TextBox ID="faa" runat="server" visible="false" ></
asp:TextBox>
</form>

</body>
</html>

and a codebehind file

using System;
using System.Data;
using System.Configur ation;
using System.Web;
using System.Web.Secu rity;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;

public partial class _HelloWorld : System.Web.UI.P age
{

protected void Page_Load(objec t sender, EventArgs e)
{
ItemFormView.Ch angeMode(FormVi ewMode.Insert);
if (!IsPostBack)
PopulateDDL();
}

private void PopulateDDL()
{
DropDownList ddl =
(DropDownList)I temFormView.Fin dControl("myDDL ");

ddl.Items.Add(" aaa");
ddl.Items.Add(" bbb");
ddl.Items.Add(" ccc");
}

}
When I run this page, the dropdown list is expected to be populated,
but it's not. However, if I remove the line

<asp:ControlPar ameter ControlID="faa" />

, it then works. It also works perfectly if using other type of
parameter, like

<asp:Paramete r Name="woo"/>

So, I don't understand what happen behind the scene. Any idea???

Thanks in advance!

Nate

Feb 2 '07 #2
On Feb 2, 11:25 am, Milosz Skalecki [MCAD] <mily...@DONTLI KESPAMwp.pl>
wrote:
Hi there,

I had a look at the System.Web.UI.W ebControls code, and it seems there's a
tiny *bug* - ConvertEmptyStr ingToNull is not used in
ControlParamete r.Evaluate() method. Let me explain the problem in details.
Every Parameter in ObjectDataSourc e.SelectParamet ers collection inherits from
System.Web.UI.W ebControls.Para meter class, which defines virtual method
protected virtual object Evaluate(HttpCo ntext context, Control control)
{
Return null;}

As you can see default implementation returns null reference, but every
derived parameter class overrides this method with its own implementation
(this mechanism is called polymorphism). For instance, ControlParamete r class
provides its own, following implementation:

protected override object Evaluate(HttpCo ntext context, Control control)
{
if (control == null)
{
return null;
}
string text1 = this.ControlID;
string text2 = this.PropertyNa me;
if (text1.Length == 0)
{
throw new
ArgumentExcepti on(SR.GetString ("ControlParame ter_ControlIDNo tSpecified", new
object[] { base.Name }));
}
Control control1 = DataBoundContro lHelper.FindCon trol(control, text1);
if (control1 == null)
{
throw new
InvalidOperatio nException(SR.G etString("Contr olParameter_Cou ldNotFindContro *l", new object[] { text1, base.Name }));
}
ControlValuePro pertyAttribute attribute1 =
(ControlValuePr opertyAttribute )
TypeDescriptor. GetAttributes(c ontrol1)[typeof(ControlV aluePropertyAtt ribute*)];
if (text2.Length == 0)
{
if ((attribute1 == null) || string.IsNullOr Empty(attribute 1.Name))
{
throw new
InvalidOperatio nException(SR.G etString("Contr olParameter_Pro pertyNameNotSpe *cified", new object[] { text1, base.Name }));
}
text2 = attribute1.Name ;
}
object obj1 = DataBinder.Eval (control1, text2);
if (((attribute1 != null) && string.Equals(a ttribute1.Name, text2,
StringCompariso n.OrdinalIgnore Case)) && ((attribute1.De faultValue != null) &&
attribute1.Defa ultValue.Equals (obj1)))
{
return null;
}
return obj1;

}

A lot of code but nothing really interesting - the only thing missing is use
of ConvertEmptyStr ingToNull. However, the problem shows up somwehere else-
in ParameterCollec tion class. As you may know every BaseDataBoundCo ntrol
(including FormView) populates the data on prerender event. Before doing so,
control performs a simple check to see if the data needs to be (re)populated
(actually this task is delegated to SelectParameter s member which is an
instance of ParameterCollec tion class, control is notified by handling
ParametersChang ed event which occurrence indicates data should be retrieved
again):

public void ParameterCollec tion.UpdateValu es(HttpContext context, Control
control)
{
foreach (Parameter parameter1 in base)
{
parameter1.Upda teValue(context , control);
}

}

And here comes the problem:

internal void Parameter.Updat eValue(HttpCont ext context, Control control)
{
object originalValue = this.ViewState["ParameterValue "];
object evaluatedValue = this.Evaluate(c ontext, control);
this.ViewState["ParameterValue "] = obj2;
if (((evaluatedVal ue == null) && (originalValue! = null)) ||
((evaluatedValu e!= null) && ! evaluatedValue. Equals(original Value)))
{
this.OnParamete rChanged();
}

}

In your case, originalValue is null, evaluatedValue is String.Empty
therefore parameter is considered as changed (TextBox.Text never returns null
reference but String.Empty, unfortunately, as I mentioned,
ControlPatamete r.Eval() method does not replace empty string with null value
even if ConvertEmptyStr ingToNull == true. It doesn't happen for Parameter
class because Parameter.Eval( ) always returns null, so the condition
if (((evaluatedVal ue == null) && (originalValue! = null)) ||
((evaluatedValu e!= null) && ! evaluatedValue. Equals(original Value)))
{
this.OnParamete rChanged();
}
is never met.

There are two easy ways to solve the problem.
1. Do not use Page_Load event to popuate the dropdownlist, use pre_render:

protected void Page_PreRender( object sender, EventArgs e)
{
if (!IsPostBack)
PopulateDDL();

}

2. Create your own parameter class derived from ControlParamete r

public class MyControlParame ter : ControlParamete r
{

protected override void LoadViewState(o bject savedState)
{
base.LoadViewSt ate(savedState) ;
}

protected override object Evaluate(HttpCo ntext context, Control control)
{
object value = base.Evaluate(c ontext, control);

if (value is String)
{
if (ConvertEmptySt ringToNull && ((string)value) == String.Empty)
return null;
else
return value;
}
else
return value;
}

}

<asp:FormView ID="ItemFormVie w" DataSourceID="m yODS" runat="server"
DefaultMode="In sert">
<InsertItemTemp late>
<asp:DropDownLi st ID="myDDL" runat="server"/>
</InsertItemTempl ate>
</asp:FormView>

<asp:ObjectData Source ID="myODS" runat="server">
<SelectParamete rs>
<cc1:MyControlP arameter ControlID="faa" PropertyName="T ext"/>
</SelectParameter s>
</asp:ObjectDataS ource>

<asp:TextBox ID="faa" runat="server" visible="true"/>
--
Milosz

"npe...@gmail.c om" wrote:
I have a simple Formview like this:
<%@ Page Language="C#" EnableViewState ="true" AutoEventWireup ="true"
CodeFile="Hello World.aspx.cs" Inherits="_Hell oWorld"%>
<html>
<body>
<form runat="server">
<asp:FormView DataSourceID="m yODS"
ID="ItemFormVie w"
runat="server">
<InsertItemTemp late>
<asp:DropDownLi st ID="myDDL" runat="server"> </
asp:DropDownLis t>
</InsertItemTempl ate>
</asp:FormView>
<asp:ObjectData Source ID="myODS" runat="server" >
<SelectParamete rs>
<asp:ControlPar ameter ControlID="faa" />
</SelectParameter s>
</asp:ObjectDataS ource>
<asp:TextBox ID="faa" runat="server" visible="false" ></
asp:TextBox>
</form>
</body>
</html>
and a codebehind file
using System;
using System.Data;
using System.Configur ation;
using System.Web;
using System.Web.Secu rity;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.W ebControls.WebP arts;
using System.Web.UI.H tmlControls;
public partial class _HelloWorld : System.Web.UI.P age
{
protected void Page_Load(objec t sender, EventArgs e)
{
ItemFormView.Ch angeMode(FormVi ewMode.Insert);
if (!IsPostBack)
PopulateDDL();
}
private void PopulateDDL()
{
DropDownList ddl =
(DropDownList)I temFormView.Fin dControl("myDDL ");
ddl.Items.Add(" aaa");
ddl.Items.Add(" bbb");
ddl.Items.Add(" ccc");
}
}
When I run this page, the dropdown list is expected to be populated,
but it's not. However, if I remove the line
<asp:ControlPar ameter ControlID="faa" />
, it then works. It also works perfectly if using other type of
parameter, like
<asp:Paramete r Name="woo"/>
So, I don't understand what happen behind the scene. Any idea???
Thanks in advance!
Nate- Hide quoted text -

- Show quoted text -
That explains!

Thanks Milosz.

Feb 6 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3117
by: pjbates | last post by:
Hi, I've been using the GridView and DetailsView controls for a while, and I'm beginning to get annoyed by the redundancy of EditItemTemplate and InsertItemTemplate in many cases. In the following code, both edit and insert templates are identical. It would be great if I could define a generic template to be used for both edits and inserts. I know that there are many situations where the edit and insert templates will differ, but for...
0
1822
by: Lee Moore | last post by:
I have the following code, which I thought should work. I get an error stating ... Could not find control 'GOAL_TEXT_CONTROL' in ControlParameter 'GOAL_TEXT'. Any help would be great. <-------------------------- Code Snippet ---------------------------> <asp:GridView ID="GridView1" Runat="server"
0
1408
by: Swetha | last post by:
Hello I have a FormView with InsertItem, EditItem and ItemTemplates. Depending on from where the page is accessed, the page opens up in either Insert, Edit or ReadOnly mode. The FormView is databound. The problem I have is when the page opens up in Insert Mode. I require one of the fields to be populated with a databound field, but for some some reason this doesnt happen in the InsertMode. Following is the FormView:
3
9867
by: K B | last post by:
Hi, I've tried this several ways but get the error that the control can't be found. I have a details view with a dropdownlist in the EditItemTemplate populated and assigned the selected value in code. I need to get the selected value when the record is saved. I've tried using the following in the SqlDataSource updating event:
1
2682
by: Cas | last post by:
Hi, How to add a controlparameter in the code-behind that is the equivalent in the aspx file of: <UpdateParameters> <asp:ControlParameter ControlID="myID" Name="myname" PropertyName="SelectedValue" Type="String" /> </UpdateParameters> Thanks
0
3240
by: Cas | last post by:
Hi, I want to create a InsertItemTemplate in a detailsview (only insertmode)programmatically. I first defined a Template, then i tried to create within that templatefield a InsertItemTemplate (but i don't know how), and finally a textbox. I did this: (Detailsview1 is defined in the .aspx file) Dim tfield As TemplateField
0
2583
by: Bart | last post by:
Hi, i want to programmatically manipulate the property 'Name' of a ControlParameter inside a InsertParameters tag. This the aspx code: ------------------ <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<% .......... %>" InsertCommand="INSERT INTO .......)"
2
2614
by: David C | last post by:
Is it possible to refer to a ControlID that is inside a FormView? If so, what is syntax? I tried to reference it just by the controlid and it created an exception with the message Could not find control 'ddlNewPropRoleID' in ControlParameter 'RoleID'. Thanks. David
0
1278
by: =?Utf-8?B?U2F0aGVlc2g=?= | last post by:
Hi all, When the below code executed it is not binding the Dropdownlist in insertitemtemplate. But the same is binding the Dropdownlist in EditItemTemplate. Also, when i use LINQDataSource in insertitemtemplate is also binding but only if i do like below it is not working... <InsertItemTemplate> <asp:DropDownList ID="DropDownList1" DataSource="<%# BindDept() %>" DataTextField="DepartmentName" DataValueField="DeptID" runat="server">
0
8611
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9031
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8876
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7741
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.