Search code examples
c#asp.netradiobuttonlist

How to avoid textbox space when it is hidden from the page?


I am hiding some labels and text boxes according to radio button selection. It hides the label and dropdown lists but the space is there. How can I hide this space? My radio button click is:

protected void rbllist_SelectedIndexChanged(object sender, EventArgs e)
{
    if (rbllist.SelectedValue == "2")
    {
        lblcode.Visible = false;
        ddempcode.Visible = false;
        lblname.Visible = false;
        ddname.Visible = false;
        lbletype.Visible = false;
        ddtype.Visible = false;
    }
    else
    {
        lblcode.Visible = true;
        ddempcode.Visible = true;
        lblname.Visible = true;
        ddname.Visible = true;
        lbletype.Visible = true;
        ddtype.Visible = true;
    }
}

Solution

  • Your problem lies somewhere else. If you set the Visible property of a control to false, it's not even rendered on the page. This means that it can't even take up space on your page. Check for a table cell or div that might take up the space instead.

    From the Control.Visible property page on MSDN:

    Gets or sets a value that indicates whether a server control is rendered as UI on the page.

    Extra:

    Your code can be written much cleaner:

    bool isVisible = !(rbllist.SelectedValue == "2");
    
    lblcode.Visible = isVisible;
    ddempcode.Visible = isVisible;
    lblname.Visible = isVisible;
    ddname.Visible = isVisible;
    lbletype.Visible = isVisible;
    ddtype.Visible = isVisible;