dynamic control's event handler not firing

T

TS

I am creating a User control and i create some dynamic controls in the init
handler. one of the controls is a custom validator which i assign a
serverValidate event handler. I usally always do my controls as custom
server controls and don't understand why this event won't fire.

I figured if the creation of the control was in the init, it would be
initialized and have its event handlers set up, then after Load, the control
would call its serverValidate handler, but i never get there.

what am i missing?

thanks a bunch!
 
W

Walter Wang [MSFT]

Hi,

Based on my understanding, you're adding a dynamic custom validator to a
User Control and fount its event is not firing, right?

Normally you just need to add the control in the Load event. My test shows
it's working correctly, here's my steps:

1) Create a simple web site
2) Create a UserControl, in its code-behind class:

protected void Page_Load(object sender, EventArgs e)
{
CustomValidator cv = new CustomValidator();
cv.ID = "CustomValidator1";
cv.EnableClientScript = false;
cv.ServerValidate += new
ServerValidateEventHandler(cv_ServerValidate);
Controls.Add(cv);
}

void cv_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
}

3) Create a WebForm, add the User Control; add a Button:

protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Page.IsValid);
}

4) View the webform in browser, when the button is clicked, it should
correctly display False since the custom validator returns false; you can
also add the breakpoint in cv_ServerValidate to verify this.

I think there must be some other difference in your project that prevents
the event from firing, maybe you could create a repro project and send it
to me. Thanks.

Sincerely,
Walter Wang ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 
T

TS

thanks walter, your code worked as well. I had to comment out lines of code
till I found that I had to comment out the .ControlToValidate property.
Having it uncommentted caused the event to be handled and having it in the
code made it so it wouldn't fire.

I usually don't supply this property but i have seen many examples using it,
though you didnt. Why does setting just this property causes the validator's
event handler from not running????

thanks!!!
 
T

TS

I did a test with a setting that property to the ID of a dynamically created
textbox and it worked. The control i was trying to set to that property was
a ListControl (depending on the situation it was a dropDownList or a
ListBox).

The help system says all of these controls are valid: TextBox, ListBox,
DropDownList, RadioButtonList, System.Web.UI.HtmlControls.HtmlInputText,
System.Web.UI.HtmlControls.HtmlInputFile,
System.Web.UI.HtmlControls.HtmlSelect and
System.Web.UI.HtmlControls.HtmlTextArea.

So why does setting the controlToValidate to the ID my ListControl
(depending on the situation it was a dropDownList or a ListBox) cause the
event from not firing?
 
S

Steven Cheng[MSFT]

Hello TS,

Sorry for the delay since Walter has been absent due to some urgent issue.
I would continue help you on this issue.

After a general overview, I understand you're developing a custom
webusercontrol (ascx based?) and in the usercontrol you programmtically
create some child controls, one of them is a customvalidator which will
validate another listcontrol(could be ListBox or dropdownlist according to
different condition). However, the custom validator's server-side validate
event handler is not called correctly, correct?

Based on your last reply, you said the problem is likely due to the
"ControlToValidate" property, when you set this property of the
customvalidator, the server-side eventhandler stop working. As far as I
know, the "ControlToValidate" is just a string which hold the control ID
against which the validator control will perform validation. Also, the
target control to validate must be in the same parent container as the
validator control so that the validator can correctly find the target
control through the ID(stored in ControlToValidate property).

Therefore, I think it is possible that the value set in the
"ControlToValidate" is not correct according to the target control's ID or
location so that the validator control can not correctly locate it at
runtime. Since I haven't your detailed code logic, just create a test web
usercontrol which simulate the code logic accordign to your description. It
contains a ListControl, a customValidator and a Button in it and the
validation is scoped in the control's own "ValidationGroup", I've tested it
on test page under the following cases:

1. put the control individually on page

2. put the control in a repeater control and use databinding to dynamically
specify whether the ListControl is a dropdownlist or listbox

Here is the user control's code(using ASP.NET 2.0) and a test page's code
fragment.(If you're using Outlook express to visit the newsgroup, you can
also get the usercontrol and page files in the attachment of this message):

============DynamicUserControl.ascx=====================
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="DynamicUserControl.ascx.cs"
Inherits="UserControl_DynamicUserControl" %>
<asp:placeHolder ID="phMain" runat="server"></asp:placeHolder>


=========DynamicUserControl.ascx.cs=============
public partial class UserControl_DynamicUserControl :
System.Web.UI.UserControl
{


protected ListControl _list = null;
protected CustomValidator _cv = null;

public bool IsDropDown
{
get { return ViewState["_isdropdown"] == null ? true :
(bool)ViewState["_isdropdown"]; }
set { ViewState["_isdropdown"] = value; }
}



protected override void CreateChildControls()
{

CreateControls();
}

protected void Page_Load(object sender, EventArgs e)
{

}

private void CreateControls()
{
phMain.Controls.Clear();

if (IsDropDown)
{
_list = new DropDownList();
}
else
{
_list = new ListBox();
}

_list.ID = "lstItems";
_list.Items.Add("aaa");
_list.Items.Add("bbbbb");
_list.Items.Add("ccccccc");
_list.Items.Add("ddddddddd");
_list.ValidationGroup = this.ID + this.GetHashCode();

phMain.Controls.Add(_list);


_cv = new CustomValidator();
_cv.ID = "cvList";
_cv.ControlToValidate = _list.ID;
_cv.ErrorMessage = "Lengh of selectedItem should > 5";
_cv.ValidationGroup = this.ID + this.GetHashCode();
_cv.ServerValidate += new
ServerValidateEventHandler(cv_ServerValidate);

phMain.Controls.Add(_cv);


Button btn = new Button();
btn.ID = "btnSubmit";
btn.Text = "Submit in usercontrol";
btn.ValidationGroup = this.ID + this.GetHashCode();

phMain.Controls.Add(btn);


}


private void cv_ServerValidate(object source, ServerValidateEventArgs
args)
{

args.IsValid = args.Value.Length > 5;
}

private void btn_Click(object source, EventArgs e)
{
Page.Response.Write("<br/>Usercontrol button is submited...");
}

}
=============================================



========test page aspx=============
<%@ Register Src="../UserControl/DynamicUserControl.ascx"
TagName="DynamicUserControl"
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">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:DynamicUserControl ID="DynamicUserControl1" runat="server"
IsDropDown="true" />
<asp:Button ID="Button1" runat="server" Text="Button" />

<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<br /><hr /><br />
<uc1:DynamicUserControl ID="uc1" runat="server" IsDropDown="<%#
Container.DataItem %>" />
</ItemTemplate>
</asp:Repeater>

</div>
</form>
</body>
</html>

================================

=====test page codebehind===============
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bool[] items = { true, false, true, false, true, true, false };

Repeater1.DataSource = items;
Repeater1.DataBind();
}
}
====================================

Please feel free to let me know if there is anything unclear above or any
other information you wonder.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead



==================================================

Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.



Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.

==================================================



This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top