Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm attempting to have an onclick event added to a row once the data is bound to a gridview webcontrol. The code below is not adding any attributes (checked the viewsource once the page is created) and, of course, no functionality is added. Right now, I've just got the onclick printing to the page, but eventually it will link to another page. Any ideas on what's wrong?

Also, thanks to the stackoverflow community at large. This community has always been a great help. Plan to go through some posts myself this weekend and start answering questions as I can to give back a bit.

C# server-side

protected void dataTbl_RowDataBound(GridViewRowEventArgs e){
            e.Row.Attributes.Add("id",e.Row.Cells[0].Text);
            e.Row.Attributes.Add("onclick", "rowClick('"+e.Row.RowIndex+"')");

        }

Javascript client-side

function rowClicked(counter){
    document.write(counter);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
457 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'm using this in the RowDataBound of my GridView, to add the attribute to select the row:

protected void grvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                //...
                break;
            case DataControlRowType.DataRow:
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#93A3B0'; this.style.color='White'; this.style.cursor='pointer'");
                if (e.Row.RowState == DataControlRowState.Alternate)
                {
                    e.Row.Attributes.Add("onmouseout", String.Format("this.style.color='Black';this.style.backgroundColor='{0}';", grvSearch.AlternatingRowStyle.BackColor.ToKnownColor()));
                }
                else
                {
                    e.Row.Attributes.Add("onmouseout", String.Format("this.style.color='Black';this.style.backgroundColor='{0}';", grvSearch.RowStyle.BackColor.ToKnownColor()));
                }
                e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(grvSearch, "Select$" + e.Row.RowIndex.ToString()));
                break;
        }
    }
    catch 
    {
        //...throw
    }
}

And this to catch de event when an user click the row:

protected void grvSearch_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        //Do wherever you want with grvSearch.SelectedIndex                
    }
    catch
    {
        //...throw
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...