Pass values from page to user control - c#

I am storing name and last name in two labels in main page. I also have those values in a class (class doesnt do much but i am using them for future expansion). I have a user control that will send an email with name and last name as body.
My question is that how can I transfer label or class variable values into user control's body variable?

Create a property on your user control with the datatype of the data you want to pass to it, and populate it in your page on creation of the control.
public class myUserControl : Control
{
...
public int myIntProperty {get; set;}
...
}
Later this in the code behind you can assign the value like
myUserControl cntrl = new myUserControl();
cntrl.myIntProperty = 5;
Instead of this you can pass the value through Markup also like
<uc1:myUserControl ID="uc1" runat="server" myIntProperty="5" />

You need to create properties on your control to hold these values; then from the page code, simply assign the values to the properties in the control.
On your control, you can have something like
public string FirstName
{
get {
if (ViewState["FirstName"] == null)
return string.Empty;
return ViewState["FirstName"].ToString();
}
set {
ViewState["FirstName"] = value;
}
}

You need to define public properties on the control and then when you use control on the page you can pass values to those parameters.
Something like:
<cc:mycustomControl runat="server"
MyProperty1=<%# label1 %>
MyProperty2=<%# label2 %>
/>

Step 1:
You can expost the values as property and than you can make use of that easily.
Step 2: To access your page from the user control you can make use of Parent property or may be some custome login to access the parent page and than write code to consume the property value.

you can do something like this in your user control
string x=((yourparentcontrol)this.parent).label1.text;
and use the string x.

Related

How to access the Items of a User Control

I have a C# Form that prints multiple instances of a User Control. Let's say that the form prints 5 instances of the User Control (Please see the link attached). How can I store/save the data inputted in all User Controls? Thanks
Here is the screenshot of the C# Form:
You'll have to store the User Controls when you instantiate them in a List or something.
You could have a class like this:
class SomeUC : UserControl
{
public SomeUC()
{
}
// A public method.
public string GetData()
{
return textBox1.Text;
}
}
Where textBox1 is the Name of a TextBox in your SomeUC
And then inside your main or something.
// Instantiate a List that will hold your UserControls, this has to be outside all methods
List<SomeUC> list = new List<SomeUC>();
// And now when you want to build your UCs
// Instantiate your UserControl
SomeUC uc1 = new SomeUC();
// Store your UserControl in a List or something (Can't help you with that)
list.Add(uc1);
Add as much as you want.
A List is not the only way you can do that, but since you don't know how many UserControls you're going to build beforehand, it makes since to use a List.
And then you can access them from the list by their index.
SomeUC uc1 = list[0];
string data = uc1.GetData();
This is an example of accessing one control (the TextBox) in your SomeUC. For other classes (such as the ComboBox) the interaction is different. Meaning you won't have a Text property in the ComboBox. You'll have to figure out things like that on youself. A little research is what it takes. You can always come back if you couldn't find a solution for something.
You can create a property like this for each item in user control.
public string DG
{
get
{
return txtDG.Text;
}
set
{
txtDG.Text = value;
}
}
Then you can access the control value by using following line in your form.
supposed you have created a usercontrol MyControl and you have placed some object of this control in FlowLayoutPenal (pnlFLP).
To get value from control
string DG = ((MyControl)pnlFLP.Controls[0]).DG;
To set value in control
((MyControl)pnlFLP.Controls[0]).DG = "1";
Try this code for accessing user control in the page
Dim txtName As TextBox = TryCast(UserControlName.FindControl("txtName"), TextBox)

Working with ListBox elements in a user control

I have a user control (ucMarket) which contains (for the purpose of simplicity) two controls: a ListBox (ucListBox) and a Label (ucLabel). I need to create multiple instances of that user control on the page dynamically (depending on the results from a DataSet), and I add them using a foreach statement and the following:
Panel1.Controls.Add(ucMarket1);
But how do I get access to the ListBox properties like Rows ? The only thing I have found so far is to cast the control as a ListBox:
ListBox listBox1 = (ListBox)ucMarket1.FindControl("ucListBox");
listBox1.Rows = 10;
For the Label part, I guess I can also do something similar:
label1 = (Label)ucMarket1.FindControl("ucLabel");
But then, how do I put that information back into the user control ? Is there a way to work directly with the user control instead of casting ?
Ok a couple of things. from a naming convention point of view, don't call the label & listbox, ucSOMETHING. This is very confusing and not clear from your example whether you're referring to the asp:Label control or some custom userControl you've written. As for accessing your controls.
I'm assuming you are creating and adding a bunch of user controls in the following manner.
for(int i = 0; i < 5; i++)
{
var control = Page.LoadControl("~/Path/To/ucMarket.ascx");
control.Id = "ucMarket" + i;
Panel1.Controls.Add(control);
}
So your best bet is to expose the Listbox on your Control as a public property.
public class ucMarket : UserControl
{
public ListBox TheListBox
{
get { return ucListBox; }
}
}
That way you could access your listbox in the following way.
var ctrl = Panel1.FindControl("ucMarket1") as ucMarket;
ctrl.TheListBox.Rows ;

How can i access a server side control from asp.net code behind file using reflection?

For example, if i have on the aspx page:
<asp:PlaceHolder ID="tab_0" runat="server" Visible="false"></asp:PlaceHolder>
<asp:PlaceHolder ID="tab_1" runat="server" Visible="false"></asp:PlaceHolder>
and i want to access these properties in the code behind page using values from a configuration file for example
string enabledTabs = "0,1,2,3";
if there a way i can use reflection to set them to enabled or disabled e.g.
foreach(var id in enabledTabs.Split(','))
{
// <use reflection to get the correct tab control>
// Set property of the tab
tab.Visible = true;
}
I could acheive the result i want by using a switch statement and setting the particular control property, but i'd like to use reflection to get the tab to make it cleaner.
Could anyone help?
Thanks!
You don't need reflection. Use Page.FindControl:
foreach(var id in enabledTabs.Split(','))
{
PlaceHolder control = (PlaceHolder)this.FindControl("tab_"+id));
control.Visible = true;
}
foreach(var id in enabledTabs.Split(','))
{
// Set property of the tab
Page.FindControl("tab_" + id.ToString()).Visible = true;
}
Try the following:
Control tab = Control.FindControl("tab_"+id);

Instantiate User Control with Custom Attributes

My User Control has the following properties:
private String _requestIP;
public String RequestIP
{
get { return _requestIP; }
set { _requestIP = value; }
}
When adding a instance of the Control to an aspx page at design time it's easy to assign the attributes which can be utilized in the codebehind file...
<uc:Item ID="Testing" runat="server" RequestIP="127.0.0.1" />
However, if I try to create the control at runtime in the aspx.cs file, how am I able to assign values to these attributes?
Control ItemX = (Control)Page.LoadControl("/controls/item.ascx");
There is no ItemX.Attributes.Add() method which I would expect to be there, and no ItemX.RequestIP property to set.
Is there a way to set this dynamically in the aspx page using <%= Users_IP_Address %> tags or some other method?
Well, you just need to cast it to the appropriate type (whatever the class name of your user control is).

Validating Form Fields in an ITemplate

I have a custom control which includes a property of the following definition:
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate Template {
get { return template; }
set { template = value; }
}
The control overrides CreateChildControls(), and adds several HtmlGenericControls and an asp:Panel control.
The actual actual implementation of the control looks something like this:
<user:Frame runat="server">
<Template>
<asp:Literal runat="server" ID="SomeControl" Text="SomeValue" />
</Template>
</user:Frame>
While the page renders as intended, it has a number of consequences of varying severity, including:
Controls enclosed within the Template cannot be referenced directly, and FindControl is required. This is fine.
I've been unable to use validation controls on them.
Is there a better way to design my custom control? Or perhaps just a way to get validation working?
By default the framework assumes that you may have more than one template in a control, like say in a Repeater. In your case you have to tell it that you intend to have a single template by using the TemplateInstance property. E.g.
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Template {
get { return template; }
set { template = value; }
}
This will allow you to reference the templated controls directly, and should fix your validation problems as well.
One way to get validation to work in this case is to add the validation controls programatically. For example:
var c = parentControl.FindControl("id");
parentControl.Controls.AddAt(
parentControl.Controls.IndexOf(c) + 1,
new RequiredFieldValidator() { ControlToValidate = c.D });

Categories

Resources