I have a GridView:
<asp:GridView ID="gridSearchResults" AutoGenerateColumns="false" DataKeyNames="uid" runat="server"
AllowSorting="true" AutoGenerateSelectButton="true" CssClass="table table-striped table-bordered"
OnRowDataBound="gridSearchResults_RowDataBound"
OnSelectedIndexChanged="gridSearchResults_UserSelected">
<Columns>
<asp:BoundField DataField="uid" HeaderText="UID" SortExpression="uid" ItemStyle-Width="30%"/>
<asp:BoundField DataField="givenName" HeaderText="First Name" SortExpression="givenName" ItemStyle-Width="35%" />
<asp:BoundField DataField="sn" HeaderText="Last Name" SortExpression="sn" ItemStyle-Width="35%" />
</Columns>
</asp:GridView>
With `AutoGenerateSelectButton="true" a "select" button appears in every row. I can click on this and fire:
`protected void gridSearchResults_UserSelected(object sender, EventArgs e) {
// Get the user's ID from the selected row
idNumber.Text = gridSearchResults.SelectedRow.Cells[1].Text;
firstName.Text = gridSearchResults.SelectedRow.Cells[2].Text;
lastName.Text = gridSearchResults.SelectedRow.Cells[3].Text;
}
which works. However, I would like to remove the "select" button and be able to press anywhere in the row to populate the TextBoxes.
This is the code for gridSearchResults_RowDataBound, which should handle the row click:
protected void gridSearchResults_RowDataBound(object objSender, GridViewRowEventArgs gridViewRowEventArgs) {
if (gridViewRowEventArgs.Row.RowType == DataControlRowType.DataRow) {
// Setup click handler and cursor
//gridViewRowEventArgs.Row.Attributes["onclick"] = DONT KNOW WHAT TO ADD HERE
gridViewRowEventArgs.Row.Attributes["style"] = "cursor:pointer";
// Implement row mouseover and mouseout
gridViewRowEventArgs.Row.Attributes.Add("onmouseover", "this.originalStyle=this.style.backgroundColor; this.style.backgroundColor='#B3E5FC';");
gridViewRowEventArgs.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalStyle;");
}
}
I have seen something like e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(grdSearchResults, "Select$" + e.Row.RowIndex);
but I'm not sure how to mix the two.
Thanks in advance for any help!
The answer can be found here; https://www.aspsnippets.com/Articles/Selecting-GridView-Row-by-clicking-anywhere-on-the-Row.aspx
For my solution I needed to modify a couple of things. In gridSearchResults_RowDataBound
I need to add:
gridViewRowEventArgs.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gridSearchResults, "Select$" + gridViewRowEventArgs.Row.RowIndex);
In gridSearchResults_UserSelected
I needed to update the Cell indices.