Finding and accessing elements of a WebUserControl - asp.net

I am creating a WebUserControl in ASP.net and want to be able to access elements of that control later. When I access them though I am trying to access them together. For example, adding a CheckBox and a table to a control and then finding the CheckBox, checking whether it has been ticked and if it has been ticked, get the values from the TextBoxes.
I currently have everything loading on the page from the custom controls, but when iterating through the controls on the page, there doesn't appear to be a control of my WebUserControl type. All of the controls are there on the page, but they exist as seperate ASP.net controls.
Am I thinking about this wrong? Is there a better way to do this?
I'm not sure this is explained very well, please feel free to ask clarifying questions.

You need to expose the user controls functionality by making public properties or functions to make it do what you need or act like you want. So for example in your case you could have a property in your user control like (you could also do a function):
public List<string> SomeValues
{
get
{
// return null if checkbox is not checked, you could just as easily return an empty list.
List<string> lst = null;
if (yourCheckBox.Checked)
{
lst = new List<string>();
// You could have something that iterates and find your controls, remember you
// are running this within your user control so you can access all it's controls.
lst.Add(yourTextBox1.Text);
lst.Add(yourTextBox2.Text);
lst.Add(yourTextBox3.Text);
// etc...
}
return lst;
}
}
Then in your page you can access your user control and call this property to get the values:
// assuming you defined your usercontrol with the 'yourUserControl' ID
List<string> lst = yourUserControl.SomeValues;
The key is to just expose what you want IN your user control so whatever is using it doesn't need to know about it's details or implementation. You should be able to just use it as you would any other control.

Related

How can same user control render different output?

Ok. Here we go. I am not sure if anyone here has implemented this, but I have a user control in my Webforms application which I am calling on several forms.
This user control has a dropdown which calls the stored procedure and filters the dropdown according to a certain date. However, on one of the forms, I want same user control to still call the stored procedure but not filter at all, just fetch all records.
Basically, I want same user control to do one thing on one form and another thing on another form. I want to use same user control since there is only small change. Rest is the same and hence I want to avoid creating another form.
Is this possible?
Thank you.
The easiest way is create a property on the user control:
public bool SOmeCOnfigurableSetting
{
get { return ((bool?)ViewState[".."]).GetValueOrDefault(false); }
set { ViewState[".."] = value; }
}
It can be any type, not just bool. In each page, set the property on the user control definition, and this controls the filtering or other functionality.

How to make a web user control public

My page contains several web user controls. Those controls contains other child controls, and those contains more child controls and so on. From my page, I want to be able to access those controls, like I do with other public classes: uc1.uc1_child1.uc1_child1_child1.Update();
(I do know about the FindControl method, and thats what Im currently using. It's however not type safe, and I need to lookup the names of the controls all the time to be on safe side. Much more time consuming than intellisense)
If you create a public property on your usercontrol for each of the usercontrols it contains, that should work.
eg
public SpecificUserControlType ContainedUserControl
{
get
{
return this.uc1_child;
}
}

iterate through all tetxbox controls in a asp.net webpage

i have 6 textboxes which i want to iterate.
they are however in a TD in a TR in a TABLE in a PANEL etc.
the only way i've figured out to iterate them is in this way:
this.Controls[0].Controls[3].Controls[7].Controls
that's not only errorprone, but also hard to come up with.
but this.FindControl (to find one by name) doesn't work either, does findcontrol also only search in the direct child, and not the whole hierarchie?
so basicly what i'm looking for is to iterate ALL controls in the page, no matter in which level of the hierarchie, to check if it's a textbox.
Is there a way to do that?
EDIT: i don't want to find them by their name (they are server controls so i could do that) because i would have to modify that code every time i add a textbox. By iterating the form i would not have to do that.
FindControl searches the hierarchy but it doesn't go into controls that are an INamingContainer
Any control that implements this interface creates a new namespace in which all child control ID attributes are guaranteed to be unique within an entire application. The marker provided by this interface allows unique naming of the dynamically generated server control instances within the Web server controls that support data binding. These controls include the Repeater, DataGrid, DataList, CheckBoxList, ChangePassword, LoginView, Menu, SiteMapNodeItem, and RadioButtonList controls.
Basically it defines a boundary to avoid naming collisions. Consider how hard it'd be if all your control IDs really had to be unique.
Note this information is also in the FindControl remarks. Tip: Always read the remarks.
The FindControl method can be used to access a control whose ID is not available at design time. The method searches only the page's immediate, or top-level, container; it does not recursively search for controls in naming containers contained on the page. To access controls in a subordinate naming container, call the FindControl method of that container.
By doing so you could navigate to the control you want going through only the naming containers & calling FindControl at each level i.e. FindControl("SomeNamingContainer").FindControl("AChildContainer")
That's not necessarily practical, and depending on what you're doing you really just need to get All TextBoxes.
IEnumerable<TextBox> TextBoxes(ControlCollection ctrls)
{
var texts = ctrls.OfType<TextBox>();
var children = ctrls.SelectMany(c => TextBoxes(c.Controls));
return texts.Union(children);
}
Try FindControl on the Page object
Page.FindControl(id)
Are they in a formview or something?
If you don't know the ID of the textboxes as well (i.e. they are dynamic) then a quick recursion code will help. I can post the code here if Page.FindControl does not work. Let me know,.
Here is the code
List<System.Web.UI.WebControls.TextBox> _textBoxes = new List<System.Web.UI.WebControls.TextBox>();
private void FindTextBoxes(ControlCollection cc)
{
foreach (Control c in cc)
{
if (c is System.Web.UI.WebControls.TextBox)
_textBoxes.Add(c as System.Web.UI.WebControls.TextBox);
else if (c.Controls.Count > 0)
FindTextBoxes(c.Controls);
}
}
You can call it as
FindTextBoxes(Page.Controls);
FindTextBoxes(MyTable.Controls);
_textBoxes collection will contain all the textboxes the code finds.
Please click the checkbox next to my answer if it solves your problem!

Add 'Current' property to ASP.NET control

I have some control. I add one instance of this control to every Page in OnInit event and I want to access this control in other places in this way: Sample.Current
public class Sample : Control
{
public static Sample Current
{
get
{
// ???
}
}
}
Can you tell me what is the best way to do this property implementation?
It would be good to have a bit more detail - what is this class' purpose? But I'll attempt to help anyway:
You'll be able to access that control from within code on the page , if it's referenced in the code and not added dynamically somehow at runtime. ie if it's a variable of the page declared like:
Sample ctrl = new Sample();
Then later you can reference it using ctrl.Current in your code.
FYI - if you want a place to reference classes and variables for a page's lifecycle, you may want to check out HttpContext.Current.Items http://www.mikeduncan.com/3-hot-uses-for-httpcontextcurrentitems-they-wont-tell-you-about/ It's like a session bag that only exists for a single page request - for example if you have a class that holds information about a user that you need to access many times from many different controls on the page, you could just stick that class into the Items collection and then reference it from any code that runs on your page.
HTH,
Lance

asp.net code behind variable

I am generating some head html in page load and because of that I query database once. in the page I query database again and put data into html with inline code.
my question is is there better way to do this? I dont want to query database everytime and reach out those filled variables from inline code. something like page.addVariable in page_load and reach those at inline like page.variables["variablename"]
thanks in advance
If I understand what you are asking, you can make an accessor and set it to Protected. That will allow you to access it from the page.
If you want to prevent calling the database on callbacks, you could always add the information to the view state on the page.
Information on the view state, hidden fields, and cookies:
http://www.csharphelp.com/archives/archive207.html
I'm not sure if this is what you're after, but you can use a HiddenField to store any data you want on the page.
Also, if you don't need it to be on the page, you can use Session or ViewState.
Here's an example of using ViewState as a property (NB. you can interchange ViewState with Session, look at the links I gave you for an explanation between the two):
public string YourProperty
{
get
{
object content = ViewState["YourProperty"];
if (content == null)
{
return string.Empty;
}
return content.ToString();
}
set
{
ViewState["YourProperty"] = value;
}
}
Note, that anything you put into ViewState or SessionState must be marked as Serializable.
If it's quite a simple class, just mark the class with the [Serializable] tag.
Is the data you retrieve from the database page specific, user specific or global to the entire application?
If the data is user specific you can use Session State.
If the data is global to the entire application you could use Application State.
Whichever you use, you can implement the data retrieval in the Session_Start (will be called only once for each user) or Application_Start (will be called only once when the web app starts) events in a Global.asax file.

Resources