问题
I want to create a gridview row where the whole row is clickable and when I click anywhere on the row it open another aspx page with the rows information.
I am using asp.net and C#. Can anyone help me please. Thanks in advance.
回答1:
Just call below code on RowDataBound to click anywhere on Gridview row to fire SelectedIndexChanged event
You have to do <%@ Page EnableEventValidation="False" %>
protected void grdYourGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Attaching one onclick event for the entire row, so that it will
// fire SelectedIndexChanged, while we click anywhere on the row.
e.Row.Attributes["onclick"] =
ClientScript.GetPostBackClientHyperlink(this.grdYourGrid, "Select$" + e.Row.RowIndex);
}
}
回答2:
fire two events of Gridview
OnRowDataBound and OnSelectedIndexChanged
Then write code in these events
protected void OnRowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex);
e.Row.ToolTip = "Click to select this row.";
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowIndex == GridView1.SelectedIndex)
{
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
row.ToolTip = string.Empty;
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
row.ToolTip = "Click to select this row.";
}
}
}
also set property EnableEventValidation = "false" in
来源:https://stackoverflow.com/questions/31720534/how-to-create-a-gridview-row-clickable