Reputation: 80
I tried to write a little function to reset the form to default. Therefore, I want to access the Controls of the page. I'm using a MasterPage. Maybe because of that, I have no access to the ContolsCollection via Page.Controls.
Any solutions for that?
Upvotes: 1
Views: 1711
Reputation: 80
Here the solution:
You have to iterate all controls and check is they have controls themselves. So you do this recursive:
public void ResetForm(ControlCollection objSiteControls)
{
foreach (Control objCurrControl in objSiteControls)
{
string strCurrControlName = objCurrControl.GetType().Name;
if (objCurrControl.HasControls())
{
ResetForm(objCurrControl.Controls);
}
switch (strCurrControlName)
{
case "TextBox":
TextBox objTextBoxControl = (TextBox)objCurrControl;
objTextBoxControl.Text = string.Empty;
break;
case "DropDownList":
DropDownList objDropDownControl = (DropDownList)objCurrControl;
objDropDownControl.SelectedIndex = -1;
break;
case "GridView":
GridView objGridViewControl = (GridView)objCurrControl;
objGridViewControl.SelectedIndex = -1;
break;
case "CheckBox":
CheckBox objCheckBoxControl = (CheckBox)objCurrControl;
objCheckBoxControl.Checked = false;
break;
case "CheckBoxList":
CheckBoxList objCheckBoxListControl = (CheckBoxList)objCurrControl;
objCheckBoxListControl.ClearSelection();
break;
case "RadioButtonList":
RadioButtonList objRadioButtonList = (RadioButtonList)objCurrControl;
objRadioButtonList.ClearSelection();
break;
}
}
}
Upvotes: 0
Reputation: 6101
By the use of master page you can not access any control by using FindControl() function because Page is within masterpage's contentPlaceHolder, so you can access all control by the use of Recursion like:
protected void Button1_Click(object sender, EventArgs e)
{
ReSetToDefault();
}
private void ReSetToDefault()
{
ResetControl(this.Page.Controls);
}
private void ResetControl(ControlCollection controlCollection)
{
foreach (Control con in controlCollection)
{
if (con.Controls.Count > 0)
ResetControl(con.Controls);
else
{
switch (con.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
{
TextBox txt = con as TextBox;
txt.Text = "default value";
}
break;
case "System.Web.UI.WebControls.CheckBox"
{
}
break;
}
}
}
}
Upvotes: 1
Reputation: 704
The ContentPlaceHolder within the master page itself contains all the page's controls, So you can access them using:
var button = ContentPlaceHolder1.FindControls("btnSubmit") as Button;
Keep in mind that the code will be running for all child pages that inherit this master page, so if one of them does not contain "btnSubmit" (in the example above), you'll get null.
Upvotes: 2