Select gridview row with no select
Ok so traditionally when you create a gridview and load data you have a commandfield which you can set as select. That "select" can be a button, image or link. Everything is fine and dandy but what happens when they ask you for no buttons and to be able to click anywhere on the row to select it? What?!!
No worries here's the answer ;)
At the top you must add this, what this does is basically avoid a horrible validation error, that .net asks to enable.
//to avoid getting validation error when selecting row in gridview protected override void Render(HtmlTextWriter writer) { for (int i = 0; i < this.gvOptions.Rows.Count; i++) { ClientScript.RegisterForEventValidation(this.gridview.UniqueID, "Select$" + i); } base.Render(writer); }
This is the error you would get if you don't add this
Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
In the aspx add a control as a select like this:
<asp:GridView ID="gvOptions" runat="server" AutoGenerateColumns="False" onrowdatabound="gridview_RowDataBound" onselectedindexchanging="gridview_SelectedIndexChanging"> <Columns> <asp:TemplateField Visible="false"> <ItemTemplate><asp:LinkButton runat="server" CommandName="select" ID="lnkSelect" Text="Select" /></ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
What that does is makes the gridview think it has a select field, but me and you know that it doesnt ;)
Now we go to the RowDataBound and just set a couple of lines
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e) { //make sure it's a datarow and not header or footer if (e.Row.RowType == DataControlRowType.DataRow) { //this makes the cursor look like the pointing finger instead of just the arrow(optional) e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';"; //this selects the row e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gridview, "Select$" + e.Row.RowIndex); } }
Almost there, finally add a select index changing to capture the id of the row selected or any value from any cell:
protected void gridview_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { //here i capture the first row cause that's where my ID is at.. lblRowId.Text = gridview.Rows[e.NewSelectedIndex].Cells[1].Text; }
Note: Remember gridview columns are based on 0 so if you want the 2nd cell its actually [1]
I don't think I have to mention this but just in case in code where you see "gridview" its the name of your gridview.. Pretty simple stuff huh?
Remember there's no problems there's just solutions ;)