Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2014-04-21
12
Medium Priority
?
291 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
  • 2
12 Comments
 
LVL 143

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 143

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 2000 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

636 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