Click Event on Row Gridview

Recent days, I got requirement to make gridview clickable and click event has to redirect user to Edit page. After few googling, I found a simple way to do it. Actually I did this for SPGridview (Sharepoint) and it’s also work for ASP gridview. I’ll try to expose the different of them in next post later.

<SharePoint:SPGridView ID="gridView" runat="server" OnRowDataBound="gridView_RowDataBound" OnSelectedIndexChanged="gridView_SelectedIndexChanged" DataKeyNames="ID" >


OnRowDataBound : will bind Select event for each row
OnSelectedIndexChanged : capture user’s Click event
DataKeyNames = “ID” : bind data ID from database into gridview as datakey, I need this ID to identify which data is clicked by user.

protected void gridView_SelectedIndexChanged(object sender, EventArgs e)
{
	// get id of data from index's row
	string id;
	id = gridView.DataKeys[gridView.SelectedRow.RowIndex].Value.ToString();
	Response.Redirect("/Pages/EditPage.aspx?itemid=" + id);

}

protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
	if (e.Row.RowType == DataControlRowType.DataRow)
	{
		// add Click Event to row
		e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(
			gridView, "Select$"+e.Row.RowIndex.ToString()));
	}
}

In others project, registering event “onclick” in RowDataBound gave me an error : Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. A workaround for this, remove RowOnDataBound and register “onclick” code to Render event.

protected override void Render(HtmlTextWriter writer)
{
     foreach (GridViewRow r in gridView.Rows)
     {
        if (r.RowType == DataControlRowType.DataRow)
        {
           r.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gridView, "Select$" + r.RowIndex.ToString(), true));                    
        }
     }
     base.Render(writer);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s