Solved

ASP.NET - C# - Disable Controls on a webpage

Posted on 2014-04-21
12
281 Views
Last Modified: 2014-04-25
I searched the internet for some code sample to disable controls on a webpage.  I found the below code and attempted to implement it but it is not working.  

Can anyone tell me why its not working?  How do I get this to work?

private void EnableControls(bool ctrlStatus)
    {
        foreach (Control c in Page.Controls)
        {
            foreach (Control ctrl in c.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;
            }
        }
    }

Open in new window

0
Comment
Question by:CipherIS
  • 5
  • 5
  • 2
12 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 40013179
each control, for which is shall work, must be "runat=server" in the definition of the .aspx file...
0
 
LVL 1

Author Comment

by:CipherIS
ID: 40013231
All my controls have "runat=server" in the .aspx file

<tr>
	<td>SSN</td>
	<td>
		<asp:textbox id="txtSSN" runat="server" columns="11" maxlength="11"></asp:textbox>
	</td>
</tr>
<tr>
	<td>First/Middle/Last</td>
	<td>
		<asp:textbox id="txtFirst" runat="server" columns="25" maxlength="50"></asp:textbox>
		<asp:textbox id="txtMiddle" runat="server" columns="5" maxlength="50"></asp:textbox>
		<asp:textbox id="txtLast" runat="server" columns="25" maxlength="50"></asp:textbox></td>
</tr>
<tr>
	<td>Address</td>
	<td><asp:textbox id="txtAddr1" runat="server" columns="50" maxlength="50"></asp:textbox></td>
</tr>
<tr>
	<td><br/>
	</td>
	<td><asp:textbox id="txtAddr2" runat="server" columns="50" maxlength="50"></asp:textbox></td>
</tr>
<tr>
	<td>City/ST/Zip</td>
	<td>
		<asp:textbox id="txtCity" runat="server" columns="20" maxlength="35"></asp:textbox>
		<asp:textbox id="txtState" runat="server" columns="2" maxlength="2"></asp:textbox>
		<asp:textbox id="txtZip" runat="server" columns="10" maxlength="10"></asp:textbox>
	</td>
</tr>
<tr>
	<td>Home/Work Phone</td>
	<td>
		<asp:textbox id="txtHome" runat="server" columns="15" maxlength="25"></asp:textbox>
		<asp:textbox id="txtWork" runat="server" columns="15" maxlength="25"></asp:textbox>
	</td>
</tr>
<tr>
	<td>Email</td>
	<td><asp:textbox id="txtEmail" runat="server" columns="50" maxlength="75"></asp:textbox></td>
</tr>
<tr>
	<td>Date of Birth</td>
	<td>
		<table cellspacing="0" cellpadding="0" width="50%">
			<tr>
				<td><asp:textbox id="txtDOB" runat="server" columns="10" maxlength="10"></asp:textbox></td>
				<td>Gender:</td>
				<td><asp:radiobuttonlist id="rblGender" runat="server" repeatdirection="Horizontal">
						<asp:listitem value="F">Female</asp:listitem>
						<asp:listitem value="M">Male</asp:listitem>
					</asp:radiobuttonlist>
				</td>
			</tr>
		</table>
	</td>
</tr>
<tr>
	<td>
		Country     
	</td>
	<td>
		<asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>
	</td>
</tr>

Open in new window

0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 40014139
and they are part of a form (that is also runat=server?)
where exactly do you run that code (which event?)
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40014265
I think the problem is most likely down to the assumption you have made about all of the controls being directly under the Page level. You'll need a recursive call to navigate the tree properly.

Change your method to:
        private void EnableControls(Control parent, bool ctrlStatus)
        {
            foreach (Control c in parent.Controls)
            {
                foreach (Control ctrl in c.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;

                    if (c.HasControls())
                        EnableControls(c, ctrlStatus);

                    //else if (ctrl is HyperLink)
                    //    ((HyperLink)ctrl).Enabled = ctrlStatus;

                    //else if (ctrl is HtmlImage)
                    //    ((HtmlImage)ctrl).Visible = ctrlStatus;
                }
            }
        }

Open in new window

And call it like:
EnableControls(Page, false);

Open in new window

0
 
LVL 1

Author Comment

by:CipherIS
ID: 40014875
@Carl Tawn - I implemented the changes but it still does not disable the controls.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40014912
Can you post the page you are trying this code on? It should work, so there must be something in your page makeup that is causing it to misbehave.
0
 
LVL 1

Author Comment

by:CipherIS
ID: 40015020
Here is the code on the page load.

protected void Page_Load(object sender, EventArgs e)
{
	if (!IsPostBack)
	{
		sqlEasyReader myEasyReader = new sqlEasyReader(connectionString);

		try
		{
			string sSQL;
			SqlDataReader myReader;

			sSQL = " SELECT person.*, usr_login ";
			sSQL += "	FROM person ";
			sSQL += "	LEFT OUTER JOIN User ON per_updateBy = User.usr_id ";
			sSQL += "   INNER JOIN country ON country.cc_id = person.cc_id " ;
			sSQL += "	WHERE per_id = " + ViewState["ID"];  
			myReader = myEasyReader.getDataReader(sSQL);

			if (myReader.Read())
			{
				txtFirst.Text = myReader["first"].ToString();
				txtMiddle.Text = myReader["middle"].ToString();
				txtLast.Text = myReader["last"].ToString();
				txtAddr1.Text = myReader["addr1"].ToString();
				txtAddr2.Text = myReader["addr2"].ToString();
				txtCity.Text = myReader["city"].ToString();
				txtState.Text = myReader["state"].ToString();
				txtZip.Text = myReader["zip"].ToString();
				txtHome.Text = myReader["phoneHome"].ToString();
				txtWork.Text = myReader["phoneWork"].ToString();
				txtEmail.Text = myReader["email"].ToString();

				if (myReader["gender"] != Convert.DBNull && myReader["gender"].ToString() == "F")
					rblGender.SelectedValue = "F";
				else
					rblGender.SelectedValue = "M";

				if (myReader["DOB"] != Convert.DBNull)
					txtDOB.Text = Convert.ToDateTime(myReader["DOB"]).ToString("d");
			}
			myReader.Close();
		}
		catch (ApplicationException ex)
		{
			lblMessage.Text = ex.Message;
			return;
		}
		catch (Exception ex)
		{
			lblMessage.Text = ex.ToString();
			return;
		}
		finally
		{
			myEasyReader.Close();
		}
	}

	this.EnableControls(Page, false);
}

Open in new window


<asp:Content ID="Content2" ContentPlaceHolderID="cphBody" Runat="Server">
<table width="85%">
    <tr align="center" class="instruction">
        <td><asp:Label ID="lblMessage" runat="server" EnableViewState="false"></asp:Label></td>
    <tr>
		<td align="center">
			<table class="smallDetail" width="90%" border="0">
				<tr>
					<td>SSN</td>
					<td>
					    <asp:textbox id="txtSSN" runat="server" columns="11" maxlength="11"></asp:textbox>
                    </td>
				</tr>
				<tr>
					<td>First/Middle/Last</td>
					<td>
					    <asp:textbox id="txtFirst" runat="server" columns="25" maxlength="50"></asp:textbox>
					    <asp:textbox id="txtMiddle" runat="server" columns="5" maxlength="50"></asp:textbox>
					    <asp:textbox id="txtLast" runat="server" columns="25" maxlength="50"></asp:textbox></td>
				</tr>
				<tr>
					<td>Address</td>
					<td><asp:textbox id="txtAddr1" runat="server" columns="50" maxlength="50"></asp:textbox></td>
				</tr>
				<tr>
					<td><br/>
					</td>
					<td><asp:textbox id="txtAddr2" runat="server" columns="50" maxlength="50"></asp:textbox></td>
				</tr>
				<tr>
					<td>City/ST/Zip</td>
					<td>
					    <asp:textbox id="txtCity" runat="server" columns="20" maxlength="35"></asp:textbox>
					    <asp:textbox id="txtState" runat="server" columns="2" maxlength="2"></asp:textbox>
					    <asp:textbox id="txtZip" runat="server" columns="10" maxlength="10"></asp:textbox>
					</td>
				</tr>
				<tr>
					<td>Home/Work Phone</td>
					<td>
					    <asp:textbox id="txtHome" runat="server" columns="15" maxlength="25"></asp:textbox>
					    <asp:textbox id="txtWork" runat="server" columns="15" maxlength="25"></asp:textbox>
					</td>
				</tr>
				<tr>
					<td>Email</td>
					<td><asp:textbox id="txtEmail" runat="server" columns="50" maxlength="75"></asp:textbox></td>
				</tr>
				<tr>
					<td>Date of Birth</td>
					<td>
						<table cellspacing="0" cellpadding="0" width="50%">
							<tr>
								<td><asp:textbox id="txtDOB" runat="server" columns="10" maxlength="10"></asp:textbox></td>
								<td>Gender:</td>
								<td><asp:radiobuttonlist id="rblGender" runat="server" repeatdirection="Horizontal">
										<asp:listitem value="F">Female</asp:listitem>
										<asp:listitem value="M">Male</asp:listitem>
									</asp:radiobuttonlist>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
		            <td>
					    Country     
				    </td>
				    <td>
				        <asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>
				    </td>
				</tr>
				<tr>
					<td colspan="2"><br/>
					</td>
				</tr>
			</table>
		</td>
	</tr>
	<tr align="center">
		<td><br/>
		</td>
	</tr>
</table>
</asp:Content>

Open in new window

0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40015064
I've just run it with the code you posted and it does indeed disable the controls. If you "View Source" the page when it is running, do you see a "readonly" attribute on any of your input fields?

Like:
<input name="ctl00$ContentPlaceHolder1$txtSSN" type="text" maxlength="11" size="11" readonly="readonly" id="ContentPlaceHolder1_txtSSN" />

Open in new window

0
 
LVL 1

Author Comment

by:CipherIS
ID: 40015263
This is what I get on View Source

<input name="ctl00$cphBody$txtFirst" type="text" value="george" maxlength="50" size="25" id="ctl00_cphBody_txtFirst" />

<input name="ctl00$cphBody$txtMiddle" type="text" maxlength="50" size="5" id="ctl00_cphBody_txtMiddle" />

<input name="ctl00$cphBody$txtLast" type="text" value="Washington" maxlength="50" size="25" id="ctl00_cphBody_txtLast" />

Open in new window

0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 40015274
Can you post the EnableControls method as you currently have it? You may also want to step through the code with the debugger and see what it is picking up in the controls collections.
0
 
LVL 1

Author Comment

by:CipherIS
ID: 40018690
Here is the method.  I did walk through the code in debug.  I have textboxes and it is not stopping under the if statement.

        private void EnableControls(Control parent, bool ctrlStatus)
        {
            foreach (Control c in parent.Controls)
            {
                foreach (Control ctrl in c.Controls)
                {
                    if (ctrl is TextBox)
                        ((TextBox)ctrl).enabled = crtlStatus

                    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;

                    if (c.HasControls())
                        EnableControls(c, ctrlStatus);

                    //else if (ctrl is HyperLink)
                    //    ((HyperLink)ctrl).Enabled = ctrlStatus;

                    //else if (ctrl is HtmlImage)
                    //    ((HtmlImage)ctrl).Visible = ctrlStatus;
                }
            }
        }

Open in new window

0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 40019520
Well the only possibility left is that your nested loop is causing it to miss the level with the control on it. So, change your method to a slightly simplified version:
        private void EnableControls(Control parent, bool ctrlStatus)
        {
            foreach (Control c in parent.Controls)
            {
                if (c is TextBox)
                {
                    (c as TextBox).ReadOnly = !ctrlStatus;
                }
                else if (c is WebControl)
                {
                    (c as WebControl).Enabled = ctrlStatus;
                }

                if (c.HasControls())
                    EnableControls(c, ctrlStatus);
            }
        }

Open in new window

0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question