ASP.NET gridview row onclick

前端 未结 4 1191
谎友^
谎友^ 2020-12-17 19:09

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

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 19:57

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

提交回复
热议问题