views:

444

answers:

2

This is a follow up to my previous question: link text

In gridview's column i have a linkbutton and a label under it.

I want to hide/unhide label when linkbutton is clicked. I use javascript because i don't want any postbacks. The code:

protected void gvwComments_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lButton =  ((LinkButton)e.Row.Cells[2].FindControl("lbtnExpand"));
            Label label = ((Label)e.Row.Cells[2].FindControl("lblBody"));
            lButton.Attributes.Add("onclick",  string.Format("HideLabel('{0}'); return false;", label.ClientID));

        }
    }



function HideLabel(button) {

            var rowObj = document.getElementById(button);


            if (rowObj.style.display == "none") {
                rowObj.style.display = "block";

            }
            else {
                rowObj.style.display = "none";

            }

        }

The problem is that when I unhide the label by clicking on button, linkbutton is shifted a a bit upper it's original position in the cell. Is it possible to preserve linkbutton's position in the gridviews cell?

A: 

I would suggest you change your CSS from display:none to display:hidden which will hide the control but maintain the space preventing the jumping around.

Michael Ciba
This is not good because hidden label with a lot text will mantain empty space in the cell, and this i don't want!
A: 

The trick is to use the keyword "this" and then get a reference to the row and change the label from there.

I have a post here, where I have a GridView with a CheckBox column and a Name column. When the CheckBox is checked the background color of the Name on that row changes. I do this starting with this attribute in the CheckBox's column:

onclick="toggleSelected(this)"

then I have a JavaScript function that finds the row and changes the next cell:

function toggleSelected(sender) {
    // note that at this point the "this" is now "sender" -which is the checkbox
    // get a reference to the row using the helper function - see below.
    var row = GetParentElementByTagName(sender, "TR");

    if (sender.checked)
        row.cells[1].className = "selected";
    else
        row.cells[1].className = '';

}

This uses the helper function:

function GetParentElementByTagName(element, tagName) {
    var element = element;
    while (element.tagName != tagName)
        element = element.parentNode;
    return element;
}

You have a slightly different requirment so you would use something like:

var lbl = row.cells[1].childNodes[0].getElementsByTagName('label')

to get a reference to your label.

JBrooks