Loop Through Controls on Web User Control - asp.net

I'm having problems looping through controls that are on my user control.
I have tried the following code, but cannot get it to find the checkboxes that are on the user control. (You can see some of my previous attempts that I have commented out.)
'For Each Ctrl As Control In Page.Controls
'For Each Ctrl As Control In Me.Page.Controls
'For Each ctrl As Control In Request.Form
'''Dim frm As Control = Me.FindControl("frmDefault")
'''For Each Ctrl As Control In frm.Controls
Dim Check As CheckBox
For Each Ctrl As Control In Me.Controls
If TypeOf Ctrl Is CheckBox Then
Check = Ctrl
' Do something here...
End If
Next
There are multiple chekcboxes on the user control. The code shown above is on the code behind page for the user control.
(The user control is being used in conjunction with my CMS, Sitecore. I'm not sure if this has any effect on the problem I am experiencing or not.)
Any suggestions?

Sitecore has no effect on walking through the control-collection, this should be possible.
Are you looping through the right Control-Collection? Is Me.Controls your Page-, UserControl- or RepeaterItems-Control collection (or another collection)?
If the checkboxes are nested in another control, you need to walk to that control-collection.
Maybe you should add your .ascx code so we can see what your control-collection looks like.

Does this bring up the names of the checkboxes?
For Each Ctrl As Control In Me.Controls
If TypeOf Ctrl Is CheckBox Then
MsgBox(Ctrl.Name)
End If
Next
That should let you know if you are hitting you checkboxes. If not rexamine your page design.
I believe you should have no problem assigning ctrl to check, it should act as a pointer to ctrl. If you have more than one checkbox on the page, do an if statement against the ctrl.name to get the correct one.

I finally figured out what is going on.
I have the checkboxes inside different tables. These tables contains runat="server". This table is inside a Div tag that also contains a runat="server".
My code could never find the checkboxes because of this. I had to add a For Each that loops through the Div tag and find the appropriate table(s). I then had to loop through the tables in order to find the checkboxes.

Some of your controls have controls. Your loop will ignore those controls. I have some extension methods I use to get all controls (you can specify type CheckBox so you don't need to do the type check in your calling code)
<Extension()> _
Public Function ChildControls(ByVal parent As Control) As List(Of Control)
Return ChildControls(Of Control)(parent)
End Function
<Extension()> _
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
Dim result As New ArrayList()
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is T Then result.Add(ctrl)
result.AddRange(ChildControls(Of T)(ctrl))
Next
Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
End Function

Well, I solved it as follows. (c#)
foreach (Control c in Page.Controls)
{
foreach (Control childc in c.Controls)
{
if (childc.ClientID == "menupadraolateral1")
{
foreach (Control cMnuLat in childc.Controls)
{
//here you can access the controls of usercontrol
}
}
}
}
Where "menupadraolateral1" is the ID used where the usercontrol is called
I hope I have helped

Related

Postback From Controls inside Composite Web Control

Let's say we have a composite web control with a combobox and a textbox. Is it possible to build into the control functionality such that when the text in the textbox changes, it posts back and adds the value as an option in the combobox?
I know that I could add an "onchange" handler to the textbox and make something work with Javascript, but that's not really what I'm looking to do. Is there a way to just put like:
Protected Sub txt1_TextChanged(sender As Object, e As System.EventArgs) Handles txt1.TextChanged
combo1.items.add(txt1.Text)
End Sub
in the web control code and it connect to the TextChanged event of the textbox?
In short yes, you should be able to do this.
I don't know what syntax you need for VB, but I have done similar things multiple times in C#. For C# you would add the name of the even handler to the markup of your text box, and set auto postback on the text box to true. Then the code behind event handler does what ever work you need it to.
As a rule I also define a custom event on the web control, and have the event handler for the textbox raise this custome event as well. This gives the option of letting the page that is using the control act on the event as well.
EDIT:
Here is an example with a DropDownList, it was part of a control to look up users within a set of Active Directory domains. If the user changed what domain they had selected we wanted it to search for the previously entered values on the new domain.
Mark-up:
<asp:DropDownList ID="ddl_Domain" runat="server" onselectedindexchanged="ddl_Domain_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
Code behind:
protected void ddl_Domain_SelectedIndexChanged(object sender, EventArgs e)
{
if (UserID != "" || LastName != "" || FirstName != "" || EmailAddress != "")
{
lnk_Find_Click(sender, e);
}
}
Or in the case where I have added a child control dynamically through code I have used this syntax:
DropDownList ddl = new DropDownList();
ddl.ID = "ddl";
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.SelectedIndexChanged += This_SelectedValue_Changed;
ddl.AutoPostBack = true;
As I said, I am not sure how to make this work with the Handles syntax of VB but it should be possible.

asp:DataPager onclick event

I am working with the .Net List view along with a data pager to enable pagination for a list view.
I am able to set the pagination working perfectly for the list view but I wish to have a method being called when ever the user clicks on any of the page numbers in the data pager.
I want to perform some operation whenever the page number is called. I guess there is no onclick event, so is there any other way by which this is possible.
Thanks
you can set it as imagebutton or linkbutton.
I have piece of code.. you just need to implement it.
you can set link and click event.
foreach (DataPagerFieldItem dpfItem in dtpPaging.Controls)
{
foreach (Control cPagerControls in dpfItem.Controls)
{
if (cPagerControls is ImageButton)
{
ImageButton imgNavigation = cPagerControls as ImageButton;
imgNavigation.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
imgNavigation.Click += new ImageClickEventHandler(imgNavigation_Click);
}
if (cPagerControls is LinkButton)
{
LinkButton lnkNumbers = cPagerControls as LinkButton;
lnkNumbers.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
lnkNumbers.Click += new EventHandler(lnkNumbers_Click);
}
}
}
You can bind a handler to the OnPagePropertiesChanging Event of the List View. A PagePropertiesChangingEventArgs object is passed to the handler as argument which contains MaximumRows and StartRowIndex properties. You can use these to calculate the current page number. It is very easy and requires no code-behind event binding as the solution proposed by sikender.

want asp dropdownlist selection to make panel visible

I have an asp dropdownlist that I would like to make a panel visible if the selection contains a certain word- how would this be possible?
lets say you have dictionary like this
List<string> words = new List<string>();
words.Add("foo");
then onchange event of drop down list
string selectedText = ddlPanel.SelectedText;
foreach(var w in words)
{
if ( w.Contains(selectedText)
{
pnl.Visible = true;
}
}
<select onchange="if (this.options[this.selectedIndex].value.indexOf('foo') != -1) document.getElementById('panel').style.display = 'block'">
Place the panel you're looking to hide within an update panel, and use the dropdownlist change as a trigger to the updatepanel. On the update, check the dropdownlist's value and set the visibility.
Either that, or if you know the ID of the panel you can manually use javascript and bind the change event to a function that checks the values and shows/hides the panel accordingly.
Create dropDownlist with two items, "visible" and "not visible" or whatever suits you and make sure to set the autopostback property to true.
Then in vb write the following on page load:
If ddlMydropdown.Text = "visible" then
panelId.Visible = true
else
panelId.Visible = false
End If
If you code in c#, you can convert this vb code to c# over at developerfusion

general method to clearform in asp.net?

I am using master page with content pages. I want to write a genral method to clear textboxes and for dropdownlist set index to 0. Please guide on this.
A Server-Side Approach
If you want to clear the TextBoxes and DropDownLists on postback, you could recurse through the page's Controls collection and for each control see if it's a TextBox or DropDownList. Here's such a function in C#:
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
else if (ctrl is DropDownList)
((DropDownList)ctrl).ClearSelection();
ClearInputs(ctrl.Controls);
}
}
To use this you'd call ClearInputs passing in the control collection you want to search. To clear out all TextBoxes and DropDownLists on the page you'd use:
ClearInputs(Page.Controls);
A Client-Side Approach
An alternative tactic would be to use a client-side approach. Namely, use JavaScript to recurse through the DOM and clear/reset the textboxes and drop-downs on this page. The following JavaScript uses the jQuery library to simplify things:
function clearElements() {
$("input[type=text]").val('');
$("select").attr('selectedIndex', 0);
}
In a nutshell, it sets the value of all <input type="text" ... /> elements on the page to an empty string and sets the selectedIndex attribute of all <select> elements on the page to 0. I've created a script on JSFiddle.net to let you try out the script: http://jsfiddle.net/xs6G9/
For More Information
I wrote a blog entry on this topic with more information and discussion. See: Resetting Form Field Values in an ASP.NET WebForm.
Happy Programming!
<input type="reset"> is a simple solution client side.

Loginview control: how to reference server side controls inside loggedintemplate

In PageLoad event of the form, I can not reference server side control within logged in template. What am I missing. So when I am logged in I will show text box control otherwise I will show text like "please login to do soso.."
Please help ..
you can use the FindControl method on your loginview control to get them...
TextBox t = (TextBox)LoginView2.FindControl("TextBox1");
string s = null;
if (t != null)
{
// textbox is in the current scope of the LoginView
s = t.text;
}
else
{
// the textbox is not in the current scope of the LoginView.
}
However, this will only work for the controls that are currently in the shown view of the LoginView control. You'd have to test that you're showing the logged in view before trying to grab the textbox, or you could also test that the FindControl doesn't return a null reference.
If you're still having trouble referencing the hidden object, you might not be entering the right value for it. Say you have a drop down list called "DropDownList1" nested inside a loggedInView. You have to set a new object that uses the FindControl method of the DropDownList class, and then use that NEW object:
DropDownList d = (DropDownList)ucLogin.FindControl("DropDownList1");
bool answer = d.SelectedValue.StartsWith("S");
if (answer == true)
{
Response.Redirect("~/MemberPages/ChangePassword.aspx");
}
In my case, I am redirecting the user to a new page if that objects selected value starts with an "S".
Works for me, and I hope it works for you!
Ben sewards

Resources