Itz.Irshad
Itz.Irshad

Reputation: 1024

How to Change Visible Property of ASP.NET Control at RunTime in .NET 3.5

A Default.aspx page has some controls. Some controls visibility depends upon conditions. Here, what is tend to accomplish is change the visible property at runtime depending upon the conditional value.

Sampel Markup (Default.aspx in Static Mode)

<div id="DivBtnImgCopy" runat="server" Visible = "True">
    <asp:ImageButton ID="BtnImgCopy" CssClass="image" ToolTip="Copy Mode" ImageUrl="img/tlb_img_copy.gif" runat="server" OnClientClick="CopyImage(); SelectButton(this,true);return false;" />
</div>

What I tried is write a method in code behind file and tried to get value from that method to set visible property to true or false.

CodeBehindFile (Default.aspx.cs)

protected bool ShowHideButton()
    {
        bool bStatus = false;
        try
        {
            if (sCondition == "false")
            {
                bStatus = false;
            }
            else if (sCondition == "true")
            {
                bStatus = true;
            }
            return bStatus;
        }
        catch { }
    }

Sample Markup (Default.aspx in Dynamic Mode)

<div id="DivBtnImgCopy" runat="server" visible = "<% =ShowHideButton() %>">
   <asp:ImageButton ID="BtnCopy" ToolTip="Copy Mode" ImageUrl="img/tlb_img_copy.gif"
                                runat="server" />
</div>

But, Getting below error: Cannot create an object of type 'System.Boolean' from its string representation '<%=ShowHideButton() %>' for the 'Visible' property.

Any solution or work-around to accomplish this task. Need Help.

Upvotes: 0

Views: 5139

Answers (2)

jbl
jbl

Reputation: 15413

Fastest way to do it is having your ShowHideButton return a bool instead of a string ; then :

 <%
  DivBtnImgCopy.Visible = ShowHideButton();
 %>

<div id="DivBtnImgCopy" runat="server" >
   <asp:ImageButton ID="BtnCopy" ToolTip="Copy Mode" ImageUrl="img/tlb_img_copy.gif"
                            runat="server" />
</div>

Cleanest way would be to include DivBtnImgCopy.Visible = ShowHideButton(); in the prerender event handler of your page

Upvotes: 1

Kek
Kek

Reputation: 3195

I am not sure of what visible does. If you want not to render the div at all, you could wrap your in a <% if %> :

<% if(ShowHideButton()) { %>
<div id="DivBtnImgCopy" runat="server">
   <asp:ImageButton ID="BtnCopy" ToolTip="Copy Mode" ImageUrl="img/tlb_img_copy.gif"
                            runat="server" />
</div>
<% } %>

Upvotes: 0

Related Questions