How to implement full row selecting in GridView without select button?
Solution 1:
You must add this on every postback and not only on databinding. Therefore you should use the RowCreated-Event of the GridView.
For example
(C#):
protected void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click to select row";
e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}
}
(VB.Net):
Private Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("onmouseover") = "this.style.cursor='pointer';this.style.textDecoration='underline';"
e.Row.Attributes("onmouseout") = "this.style.textDecoration='none';"
e.Row.ToolTip = "Click to select row"
e.Row.Attributes("onclick") = Me.Page.ClientScript.GetPostBackClientHyperlink(Me.GridView1, "Select$" & e.Row.RowIndex)
End If
End Sub
Solution 2:
Instead of doing it on RowCreated
, you could do it on Render()
. That way you could use the overload of GetPostBackClientHyperlink
with true on registerForEventValidation
and avoid the "invalid postback/callback argument" error.
Something like this:
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
r.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
r.Attributes["onmouseout"] = "this.style.textDecoration='none';";
r.ToolTip = "Click to select row";
r.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + r.RowIndex,true);
}
}
base.Render(writer);
}
Solution 3:
<style type="text/css">
.hiddenColumn
{
display: none;
}
.rowGrid
{
cursor: pointer;
}
</style>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="true" >
<RowStyle CssClass="rowGrid" />
<Columns>
<asp:CommandField ButtonType="Button" ShowSelectButton="true" HeaderStyle-CssClass="hiddenColumn"
ItemStyle-CssClass="hiddenColumn" FooterStyle-CssClass="hiddenColumn" />
</Columns>
</asp:GridView>
<script type="text/javascript">
$(function () {
$("#<%= GridView1.ClientID %> tr.rowGrid")
.live("click", function (event) {
$(this).find("input[type='button'][value='Select']").click();
});
$("#<%= GridView1.ClientID %> input[type='button'][value='Select']")
.live("click", function (event) {
event.stopPropagation();
});
});
</script>