In the post Enable / Disable all controls in an Asp.Net Page, we saw how to Enable/Disable controls
in an Asp.net page, there are situations in which we load User Controls in the
main page, in these situations the normal approach will not enable/disable the
nested/child controls in the User Control, since the user control will be
treated as a single control in the asp.net page.
To Enable/Disable the child controls within
the user control, we need to iterate through the controls in the user control
and Enable/Disable them separately. Identify the control from the page using
Page.FindControl(), and pass the control to the EnableUserControls()
method.
ucMyControl objMyControl = (ucMyControl)Page.FindControl("ucMyControl");
if (strMode.ToUpper() == "VIEW"))
if (strMode.ToUpper() == "VIEW"))
{
EnableUserControls(false, objMyControl)
}
else if (strMode.ToUpper() == "EDIT"))
{
EnableUserControls(true, objMyControl)
}
else if (strMode.ToUpper() == "EDIT"))
{
EnableUserControls(true, objMyControl)
}
Based on the mode VIEW/EDIT we
will pass false/true to the EnableUserControls function,
and the same will DISABLE/ENABLE controls
in the page.
public void
EnableUserControls(bool status, UserControl currControl)
{
foreach (Control ctrl in currControl.Controls)
{
foreach (Control ctrl in currControl.Controls)
{
if (ctrl is TextBox)
((TextBox)ctrl).ReadOnly = (ctrlStatus == true) ? false : true;
else if (ctrl is Button)
((Button)ctrl).Enabled = ctrlStatus;
else if (ctrl is RadioButtonList)
((RadioButtonList)ctrl).Enabled = ctrlStatus;
else if (ctrl is ImageButton)
((ImageButton)ctrl).Enabled = ctrlStatus;
else if (ctrl is CheckBox)
((CheckBox)ctrl).Enabled = ctrlStatus;
else if (ctrl is DropDownList)
((DropDownList)ctrl).Enabled = ctrlStatus;
else if (ctrl is HyperLink)
((HyperLink)ctrl).Enabled = ctrlStatus;
else if (ctrl is HtmlImage)
((HtmlImage)ctrl).Visible = ctrlStatus;
}
}
}
Notice the we are setting the .Enabled property
for all other controls except the textBox control, when a TextBox is disbled
the contents in the TextBox will not be clearly visible to the users hence we
are setting the ReadOnly property for the TextBox,
and this functions opposite to the Enable/Disable
If Enable is set to true then ReadOnly should be set to false
If Enable is set to false then ReadOnly should be set to true
If Enable is set to false then ReadOnly should be set to true
To achieve this we are using a conditional
operator to reverse the value for the ReadOnly property.
((TextBox)ctrl).ReadOnly = (ctrlStatus == true) ? false: true;
Related Post
No comments:
Post a Comment