65.9K
CodeProject is changing. Read more.
Home

Adding click event to rows in a DataGrid

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.07/5 (8 votes)

Jul 11, 2006

CPOL
viewsIcon

30591

A simple way to select a DataGrid row by clicking it.

Introduction

I spent some time trying to find a way to simulate FullRowSelect on a DataGrid, and couldn't really see any obvious way of doing it (all the solutions I tried were pretty complicated, and crashed half of the time), but after a while, it hit me that you could use JavaScript. All you need to do is:

protected void nameOfGridView View_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand'");
        e.Row.Attributes.Add("onclick", "javascript:__doPostBack" +
           "('nameOfGridView '"
           + ", 'Select$" + e.Row.RowIndex + "')");
    }
}

Just add this method to the RowDataBound Delegate for your DataGrid, and replace nameOfGridView with the name of your GridView. That's all, easy!