How to add a Requiredfieldvalidator to a Custom Dropdownlist - asp.net

I've tried to create a custom control which inherits from DropDownList. In this control I want to add a RequiredFieldValidator.
If I delete the marked line, the page will be rendered, but the Validator doesn't work. With the marked line the following error occurred:
System.Web.HttpException: TEST lässt keine untergeordneten Steuerelemente zu.
public class TEST: DropDownList
{
private RequiredFieldValidator rfv;
protected override void OnInit(EventArgs e)
{
rfv = new RequiredFieldValidator();
rfv.ID = this.ClientID;
rfv.ControlToValidate = ID;
rfv.Display = ValidatorDisplay.Static;
rfv.SetFocusOnError = true;
rfv.InitialValue = "";
rfv.CssClass = "validator";
rfv.ValidationGroup = ValidationGroup;
--> Controls.Add(rfv); <--
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
rfv.RenderControl(writer);
}
}
I developed a similar control which inherits from TextBox, and there it works fine (with the marked line).

Related

Set value to TextBox in UserControl inside placeholder

I have an textbox inside an user control. I created dinamically this user control and load in placeholder.
But when I tried to assign a value to the textbox, I raised next below error:
Object reference not set to an instance of an object
This is the user control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="IVT_FormClient.ascx.cs" Inherits="Evi.Sc.Web.Evi.IVT.Sublayouts.IVT_FormClient" %>
<asp:Panel ID="pnlContainer" runat="server">
<asp:TextBox ID="txtClientNumber" runat="server"></asp:TextBox>
</asp:Panel>
The access modifier is (In the user control):
public string TxtFirstName
{
get { return txtFirstName.Text; }
set { txtFirstName.Text = value; }
}
In the web form I have the control reference:
<%# Reference Control="~/Evi/IVT/Sublayouts/IVT_FormClient.ascx" %>
In the code behind of the user control is:
public partial class frm_VerifyIdentity : System.Web.UI.Page
{
IVT_FormClient ivtFormClient = new IVT_FormClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
IVT_FormClient ivtFormClient = (IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}
}
}
The error occur is this line of code:
ivtFormClient.TxtFirstName = UserClient.FirstName;
Do not create an instance of a UserControl via constructor but with LoadControl as you have already done in Page_Load. However, you are doing that only if(!IsPostBack). Hence the control is instantiated the next postback via constructor.
Also, you have to recreate dynamic controls on every postback. I would suggest to add the UserControl delaratively to the page. You can hide/show it accordingly. Otherwise you need to create/add it always, best in Page_Init instead of Page_Load.
So this is not best-practise(just add it to the page) but should work as desired:
IVT_FormClient ivtFormClient = null;
protected void Page_Init(object sender, EventArgs e)
{
ivtFormClient =(IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}

CustomValidator on server control rendering inside tags of parent element

I have a RadEditor and I'm trying to add a CustomValidator to it, as so:
protected override void OnInit(EventArgs e)
{
var validator = new CustomValidator();
validator.CssClass = "validator-error";
validator.Display = ValidatorDisplay.Dynamic;
validator.ControlToValidate = ".";
validator.Text = "You've exceeded the maximum allowed length for this field";
validator.ClientValidationFunction = "radEditorCheckLength";
this.Controls.Add(validator);
base.OnInit(e);
}
Which works fine, however when it renders, the validator is actually rendering inside the RadEditor. How do I make it appear before the RadEditor element?
This is a total hack. Does it work?
protected override void Render(HtmlTextWriter writer)
{
this.validator.RenderControl(writer);
this.validator.Visible = false;
base.Render(writer);
this.validator.Visible = true;
}
You'll need to store your CustomValidator in a field:
private CustomValidator validator;
protected override void OnInit(EventArgs e)
{
this.validator = new CustomValidator();
// ...
}
(I disassembled RadEditor in Reflector, but I didn't see an easy way to modify RenderChildren to skip rendering the validator.)

passing a value to WebUserControl for show in a lable

hi
i have a WebUserControl that have a lable for show message
how can i send a value to the lable from Page to my WebUserControl at runtime.
In the code behind file of your control you can specify an attribute
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public String customType
{
get
{
String s = (String)ViewState["customType"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["customType"] = value;
}
}
And after you can get this attribute to fill your label in the pageload with
mylabel.text = mycontrol.customType
In the asp page you specify the attribute (here is the 'customType'):
<wuc:ContSign customType="person" ID="ContSignPanel" runat="server" />
MSDN
You can create a public method in your user control such as
public void ShowMessage(string message)
{
Label1.Text = message;
}
Label1 being the label control in user control. Now you can use the method from Page as and when you need it - for example,
protected void Page_Load(object Sender, EventArgs e)
{
MyUserControl1.ShowMessage("Hello");
}
where MyUserControl1 is the name/ID of web user control put on the page.
just make a property to get and set values for the lable in the user control
private string _labelmsg;
public string LableMsg
get
{
return _labelmsg;
}
set
{
_labelmsg=lblID.Text;
}
and then set in the aspx.cs page like
UserControlID.LabelMsg="Set Any Value";

ASP CompositeControl & ScriptManager

I'm really new to the WebControl / CompositeControl world, and I have a small test class I am playing with. It's just a LinkButton that updates when clicked. Things work great when I leave it out of UpdatePanel. But when I try to run it inside I still get a full page POST response. How can I make this class work inside a UpdatePanel?
Here's the class:
public class Test2 : CompositeControl
{
private static readonly object testButtonEvent = new object();
public event EventHandler OnTestClick
{
add { Events.AddHandler(testButtonEvent, value); }
remove { Events.RemoveHandler(testButtonEvent, value); }
}
private LinkButton testLinkButton;
public virtual string testLinkButtonText
{
get
{
object o = ViewState["testLinkButtonText"];
return (o == null) ? String.Empty : (string)o;
}
set
{
if (value == null)
ViewState.Remove("testLinkButtonText");
else
ViewState["testLinkButtonText"] = value;
}
}
protected override void OnInit(EventArgs e)
{
/* This stuff makes it ajax friendly but stops the text rendering
EnsureChildControls();
ScriptManager ScMan = ScriptManager.GetCurrent(Page);
if (ScMan != null)
{
ScMan.RegisterAsyncPostBackControl(testLinkButton);
} */
base.OnInit(e);
}
protected override void CreateChildControls()
{
Controls.Clear();
testLinkButton = new LinkButton();
testLinkButton.Command += new CommandEventHandler(testClick);
testLinkButtonText = "Test ViewState Text";
Controls.Add(testLinkButton);
}
void testClick(object sender, CommandEventArgs e)
{
testLinkButtonText = "Updated Text On " + DateTime.Now.ToLongTimeString();
}
protected override void Render(HtmlTextWriter writer)
{
RenderContents(writer);
}
protected override void RenderContents(HtmlTextWriter writer)
{
EnsureChildControls();
testLinkButton.Text = testLinkButtonText;
testLinkButton.RenderControl(writer);
}
}
The code in OnInit() causes the control to post correctly, but I don't get the updated text for the LinkButton. It is still firing off the event - when I debug I can see it being called. What's the proper way to set this control up for use in a UpdatePanel?
Usage, just in case:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<cc:Test2 ID="jqTest02" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
You have to give the button an ID property...this is used in the client-side javascript that drives the UpdatePanel. More specifically, it's listed in the list of controls to intercept and do async postbacks for.
testLinkButton.ID = "btn";

LinkButton.Command in user control (ascx) will not call specified method

I have the following code:
public partial class queryTerm : System.Web.UI.UserControl
{
private static readonly List<string> BooleanOperators = new List<string> { ".", "AND", "AND NOT", "OR", "OR NOT" };
protected void BuildBoolPanel()
{
var parensOpen = _labelBoolean.Text;
foreach (var #operator in BooleanOperators)
{
if (parensOpen == #operator)
{
continue;
}
var linkButton = new LinkButton();
linkButton.Text = #operator;
linkButton.CommandArgument = #operator;
linkButton.CommandName = "parensOpen";
linkButton.Command += new CommandEventHandler(linkButton_Command);
_popupMenuParensOpen.Controls.Add(linkButton);
var literalLineBreak = new Literal();
literalLineBreak.Text = "<BR/>";
_popupMenuParensOpen.Controls.Add(literalLineBreak);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
BuildBoolPanel();
}
void linkButton_Command(object sender, CommandEventArgs e)
{
_labelBoolean.Text = (string)e.CommandArgument;
BuildBoolPanel();
}
}
I have a panel(it's _popupMenuParensOpen) that is shown with the hoverextender whenever the cursor finds itself over a specific label in my user control.
This panel has all the boolean operators and '.' meaning not set.
I programatically add the boolean operators as a label in my panel, and I only add those that don't match what it is currently set to. For instance if my label is set to 'AND', when I hover over it, I display everything but 'AND'.
The problem is these never call linkButton_Command even though I instruct them to.
Weirder yet, if I remove the 'if (!this.IsPostBack) in page load, it will call it.
My control is inside an updatePanel.
The issue is that you're dynamically adding the controls during the Page_Load event. When a postback occurs those controls aren't going to exist and will need to be created every time. This is why when you remove your if (!Page.IsPostBack), and the controls are rebuilt, it works.
Since you're building this as a user control, you might want to look in to overriding the CreateChildControls method.

Resources