passing a value to WebUserControl for show in a lable - asp.net

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

Related

How to assign the value of user control property to aspx or codebehind in VB?

I have a user control with a public property which updates each time when a date from my calender(part of user control) is selected. Now I need to bring this value to page on which this user control is kept. How to do this.
I tried bringing the property value on page load event of aspx.vb(master page on which user control is present) but couldn't do it as page load is happening first and user property is loading next(null reference exception).
i tried this on page load of aspx hdnPPSeq.Value = PPCalender1.test1.ToString
Please share ideas to bring this value to aspx or codebehind in vb.
Create a method in usercontrol, which will return property value.
public partial class PassPropertyToPage : System.Web.UI.UserControl
{
string strSelectDateTime;
public string SelectedDateTime
{
set { strSelectDateTime = value; }
get { return strSelectDateTime; }
}
protected void Page_Load(object sender, EventArgs e){}
public string GetDateTime()
{
strSelectDateTime = <calendar value>;
return strSelectDateTime;
}
}
And in page, call the method to get the value:
public partial class AccessUserControlProperty : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("DateTime selected in page: " + PassPropertyToPage1.GetDateTime() + "<br/>");
}
}

How to add a Requiredfieldvalidator to a Custom Dropdownlist

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

textBox onBlur to call server method instead of client method

I'm extending a web control. I need to call server methods on every event fired by the control instead of javascript.
public partial class MyTextBox : RadTextBox, IScriptControl
{
public MyTextBox()
{
Attributes.Add("onBlur", "handleLostFocus();");
Attributes.Add("runat", "server");
}
public void handleLostFocus()
{
MyObject obj = new MyObject();
obj.someproperty = this.Text; //or somehow get the user entered text.
MyService1 service = new MyService1();
service.sendRequest(obj);
}
}
As I said in my comment, TextBox will post by default if AutoPostBack = "True", however, you need to handle your event. Supposing your TextBox is named TextBox1:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
string str = TextBox1.Text;
}
Get rid of handleLostFocus() or have it be the handler for your TextBox control.
Good luck mate.

Store and transfer values in a ascx control

I have a problem that I have been struggling with for some time, and it is regarding transfering values from one control to another.
Basically I have two .ascx controls. On control1: I have an email textbox called txtEmail. The txtEmail is used to save the email in the SQL table, and on update button click, I load Control2 that has a email textbox as well. I need the emailtext box from control1 to be available on email textbox on control2.
I have tried all kinds of different ways but to no avail. I even tried using delegates and events but I can't make it work.
Does anyone know how I can do this.
Regards
Please find below the code:
public event EventHandler Notify;
public string Email
{
get { return txtEmail.Text; }
set {Email= value ; }
}
//button that will handle the update
protected void btnUpdateDB_Click(object sender, EventArgs e)
{
var email = txtEmail.Text.ToString();
public BaseClass.BAL.MBAL m = new BaseClass.BAL.MBAL();
var s = new BaseClass.Controllers.m();
s.email=email;
if(m.save(s)!=0) txtMsave.Text="Saved....";
}
//second control
public void notifyEmailChange(object sender,EventArgs e)
{
txtUsername.Text = member1.Email;
}
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
member1.Notify += new EventHandler(notifyEmailChange);
}
}
public string email {
set { txtUsers.Text = value; }}
Maybe I am trivializing the problem, but if you are wanting to be able to read/write to the text box on each of the custom controls, just make a public property that reads and writes to the textbox on each of the two controls.
public string EmailAddress {
get {
return txtEmailAddress.Text;
}
set {
txtEmailAddress.Text = value;
}
}
Now the page that contains the two controls can read the email address from the first control and write it into the email address text box in the second control.
If I am misunderstanding the problem, let me know.
The way that I have done this in the past is to have
UserControl1 have a custom event called (for instance) Notify.
The containing control wires Notify to an EventHandler
When notify fires (on the update) the consuming event handler fires and this event handler updates the email on UserControl2
Might seem overengineered but because UserControl2 can't "see" UserControl1 I think this is the way to go
Example
In UserControl1
public event EventHandler Notify;
and within the update button click event handler
if(Notify != null)
{
Notify(this, new EventArgs());
}
In parent control
in Page_Load
ucUserControl2.Notify += new EventHandler(NotifyUserControl);
and to set the message
protected void NotifyUserControl(object sender, EventArgs args)
{
ucUserControl2.Email = ucUserControl1.Email;
}
You obviously need public properties in UserControls to expose the Email text

Custom TextBox with built-in Validator: server side validation not firing

I have a class that looks like this:
public class TextField : TextBox
{
public bool Required { get; set; }
RequiredFieldValidator _validator;
protected override void CreateChildControls()
{
base.CreateChildControls();
_validator = new RequiredFieldValidator();
_validator.ControlToValidate = this.ID;
if(Required)
Controls.Add(_validator);
}
public override void Render(HtmlTextWriter tw)
{
base.Render(tw);
if(Required)
_validator.RenderControl(tw);
}
}
This has been working for a while in a internal application where javascript is always enabled. I recently noticed that an upstream javascript error can prevent the validators from firing, so the server side validation should kick in... right? right?
So the Page.IsValid property always returns true (I even tried explicitly calling Page.Validate() before-hand).
After some digging, I found that the validator init method should add the validator to the page, but due to the way I'm building it up, I don't think this ever happens. Thus, client side validation works, but server side validation does not.
I've tried this:
protected override OnInit()
{
base.OnInit();
Page.Validators.Add(_validator); // <-- validator is null here
}
But of course the validator is null here (and sometimes it's not required so it shouldn't be added)... but OnInit() is really early for me to make those decisions (the Required property won't have been loaded from ViewState for example).
Ideas?
The CreateChildControls is basically for the controls that have childs. RequiredFieldValidator is like a sibling to TextBox.
Here is the code that works for me:
public class RequiredTextBox : TextBox
{
private RequiredFieldValidator _req;
private string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
protected override void OnInit(EventArgs e)
{
_req = new RequiredFieldValidator();
_req.ControlToValidate = this.ID;
_req.ErrorMessage = _errorMessage;
Controls.Add(_req);
base.OnInit(e);
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
_req.RenderControl(writer);
}
}
And here it the ASP.NET page behind:
protected void SubmitClick(object sender, EventArgs e)
{
if(Page.IsValid)
{
// do something
}
}
And here is the ASPX code:
<MyControl:RequiredTextBox runat="server" ErrorMessage="Name is required!" ID="txtName"></MyControl:RequiredTextBox>
<asp:Button ID="Btn_Submit" runat="server" Text="Submit" OnClick="SubmitClick" />
Validators have to inherit from BaseValidator.

Resources