Monday 19 February 2007

Grid-View : Select a row without "Select link"

You can use javascript to select a row in a grid-view by setting the rows onMouse and onCLick events:


protected void gvSettings_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvSettings, "Select$" + e.Row.RowIndex);
}
}


When DataBind() is called on the grid the events will be set for each row.
Code taken from this Geekzilla article


.... further to this, if 'EnableEventValidation="true"' is on , which it is by default, the postback will cause an error: "Invalid postback or callback argument"


to overcome this you need to register each PostBack event in the Render fn of the page:


foreach (GridViewRow r in gvSettings.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation(this.gvSettings.UniqueID,"Select$" + r.RowIndex);
}
}