Solved

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

Posted on 2014-04-21
12
278 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Class object 2 26
About delegates in c sharp 3 33
Replace &lt; with < 14 55
C# MVC and a global static factory that never dies 4 46
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.
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

911 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

19 Experts available now in Live!

Get 1:1 Help Now