Solved

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

Posted on 2014-04-21
12
276 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]
Comment Utility
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
Comment Utility
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]
Comment Utility
and they are part of a form (that is also runat=server?)
where exactly do you run that code (which event?)
0
 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
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
Comment Utility
@Carl Tawn - I implemented the changes but it still does not disable the controls.
0
 
LVL 52

Expert Comment

by:Carl Tawn
Comment Utility
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:CipherIS
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

771 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now