Select GridView Row Without Postback OnClick Of Cell JavaScript Posted by amiT jaiN This Example explains how to Select GridView Row On Click Of Cell Programmatically Without Postback Using JavaScript In Asp.Net. We can make cells clickable by adding OnClick attribute in ClientScript. Place ScriptManager And UpdatePanel on the page and add Gridview inside ContentTemaplatefor partial postbacks, Populate it using SqlDataSource. HTML SOURCE OF GRIDVIEW 1: <asp:ScriptManager ID="ScriptManager1" runat="server"/> 2: <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 3: <ContentTemplate> 4: 5: <asp:GridView ID="GridView1" runat="server" 6: AutoGenerateColumns="False" 7: DataKeyNames="EmployeeID" 8: DataSourceID="SqlDataSource1" 9: onrowdatabound="GridView1_RowDataBound" 10: AllowPaging="True" 11: onpageindexchanging="GridView1_PageIndexChanging"> 12: <Columns> 13: <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID"/> 14: <asp:BoundField DataField="FirstName" HeaderText="FirstName"/> 15: <asp:BoundField DataField="City" HeaderText="City"/> 16: <asp:BoundField DataField="Country" HeaderText="Country"/> 17: </Columns> 18: </asp:GridView> 19: 20: <asp:SqlDataSource ID="SqlDataSource1" runat="server" 21: ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Select GridView Row Without Postback OnClick Of Cell JavaScript
Posted by amiT jaiNThis Example explains how to Select GridView Row On Click Of Cell Programmatically Without Postback Using JavaScript In Asp.Net.
We can make cells clickable by adding OnClick attribute in ClientScript.
Place ScriptManager And UpdatePanel on the page and add Gridview inside ContentTemaplatefor partial postbacks, Populate it using SqlDataSource.
01Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)02 If e.Row.RowType = DataControlRowType.DataRow Then03 e.Row.Attributes("onmouseover") = "this.style.cursor='hand';"04 e.Row.Attributes("onmouseout") = "this.style.textDecoration='none';"05 06 e.Row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(Me.GridView1, "Select$" & Convert.ToString(e.Row.RowIndex))07 End If08End Sub09 10Protected Sub GridView1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)11 GridView1.SelectedIndex = -112End Sub
While running this code we get EventValidation error.
Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> 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.
We can fix this by setting EnableEventValidation="false" in page directive but it will be a security risk, so there are other ways to handle this.
Method 1.
Add this style in head section of page 1: <style> 2: .visibility {Display : none} 3: </style>
Now add ShowSelectButton Commandfield column in gridview source and set it's css propertyto style we added in head. this will hide the select button. 1: <asp:CommandField ShowSelectButton="True" 2: ItemStyle-CssClass="visibility"/>
Method 2.
Remove the code from RowDataBound Event of GridView and OverRide Render event of page, set the last parameter (bool registerForEventValidation) of ClientScript to true.
01Protected Overrides Sub Render(textWriter As System.Web.UI.HtmlTextWriter)02 For Each gvRow As GridViewRow In GridView1.Rows03 If gvRow.RowType = DataControlRowType.DataRow Then04 gvRow.Attributes("onmouseover") = "this.style.cursor='hand';"05 gvRow.Attributes("onmouseout") = "this.style.textDecoration='none';"06 gvRow.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + gvRow.RowIndex, True)07 End If08 Next09 MyBase.Render(textWriter)10End Sub
ASP.NET: Selecting a Row in a GridViewPosted Mon, Jan 25 2010 13:25 by Deborah Kurata
Once I had my ASP.NET GridView in place (see this prior post), the next thing I wanted to do was select a row and go to a review/edit page. But I didn't want to add the "Select" or "Edit" buttons. It seemed more natural for the users to simply click on the row.
I used Bing and followed my always helpful "guess and check" method. I found quite a few links to solutions for clicking on a row in the GridView control. Some didn't work at all. Some worked if you turned off enableEventValidation. Some worked only if you did not try to page the results.
Here is a simple solution that works with any GridView and supports paging. It goes into the code behind file for the page containing the GridView. In this example, the GridView is called "CustomerGridView".
In C#:
protected override void Render(System.Web.UI.HtmlTextWriter writer) { foreach (GridViewRow row in CustomerGridView.Rows) { if (row.RowType == DataControlRowType.DataRow) { row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';"; row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; // Set the last parameter to True // to register for event validation. row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(CustomerGridView, "Select$" + row.DataItemIndex, true); } } base.Render(writer); }
In VB:
Protected Overrides Sub Render(ByVal writer As _ System.Web.UI.HtmlTextWriter) For Each row As GridViewRow In CustomerGridView.Rows If row.RowType = DataControlRowType.DataRow Then row.Attributes("onmouseover") = _ "this.style.cursor='hand';this.style.textDecoration='underline';" row.Attributes("onmouseout") = _ "this.style.textDecoration='none';"
' Set the last parameter to True ' to register for event validation. row.Attributes("onclick") = _ ClientScript.GetPostBackClientHyperlink(CustomerGridView, _ "Select$" & row.DataItemIndex, True) End If Next
MyBase.Render(writer) End Sub
This code overrides the Render method for the page. It loops through each of the rows in the GridView. It sets the onmouseover and onmouseout attributes so that the user sees that the row is clickable while moving the mouse over the grid rows.
The key attribute, however, is the onclick. Setting this attribute to GetPostBackClientHyperlink allows you to get a server-side click event on the row.
The first parameter to this method is the name of the GridView control. For this example, it is CustomerGridView.
The second parameter defines the name of the command, a "$" separator, and the command argument.
NOTE: In many examples I found, the command argument is set to row.RowIndex instead of row.DataItemIndex. This does not work if your GridView is paged because RowIndex is reset to 0 for the first item on each page.
Set the last parameter of the GetPostBackClientHyperlink method to true to register the event for validation. By setting this, you don't have to turn off enableEventValidation.
You can then catch this event using the RowCommand.
In C#:
private void CustomerGridView_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e) { if (e.CommandName == "Select") { // Get the list of customers from the session List<Customer> customerList = Session["Customers"] as List<Customer>;
In C#, you also need to set up the event handler. In this example, the event handler is set up in the Page_Load event, but you could put it where it makes sense for your application.
Private Sub CustomerGridView_RowCommand(ByVal sender As Object, _ ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _ Handles CustomerGridView.RowCommand If e.CommandName = "Select" Then ' Get the list of customers from the session Dim customerList As List(Of Customer) customerList = TryCast(Session("Customers"), _ List(Of Customer))
Debug.WriteLine(customerList(CType(e.CommandArgument, Integer)).LastName) End If End Sub
This code first gets the customer list from the session. You can get the GridView information from wherever you have it defined, such as the ViewState. A Debug.WriteLine statement demonstrates how to access theCommandArgument. In a real application, you would use the CommandArgument to display the Review/Edit page for the selected customer.
Use this technique any time you want to handle a click event on an ASP.NET GridView row.
Gets a reference to a GridViewRow object that represents the selected row in the control.Namespace: System.Web.UI.WebControlsAssembly: System.Web (in System.Web.dll)
// Get the currently selected row using the SelectedRow property. GridViewRow row = CustomersGridView.SelectedRow;
// Display the company name from the selected row. // In this example, the third column (index 2) contains // the company name. MessageLabel.Text = "You selected " + row.Cells[2].Text + ".";
// Get the currently selected row. Because the SelectedIndexChanging event // occurs before the select operation in the GridView control, the // SelectedRow property cannot be used. Instead, use the Rows collection // and the NewSelectedIndex property of the e argument passed to this // event handler. GridViewRow row = CustomersGridView.Rows[e.NewSelectedIndex];
// You can cancel the select operation by using the Cancel // property. For this example, if the user selects a customer with // the ID "ANATR", the select operation is canceled and an error message // is displayed. if (row.Cells[1].Text == "ANATR") {
<!-- This example uses Microsoft SQL Server and connects --> <!-- to the Northwind sample database. Use an ASP.NET --> <!-- expression to retrieve the connection string value --> <!-- from the Web.config file. --> <asp:sqldatasource id="CustomersSource" selectcommand="SELECT CustomerID, FirstName, MiddleName, LastName, Phone FROM SalesLT.Customer" connectionstring="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>" runat="server"/>
</form> </body></html>
Home Development Technology Hot Topics Login
Select a row in an asp:GridView without using a Select Command
ASP.Net's GridViews can be quite useful, but beware of binding them to huge
datasets as this has an overhead on the ViewState.
Often you'll want to display a number of columns on each line and row space
becomes an issue. What's worse is you then have to create a SELECT command
button to be able to access that line's data.
<asp:CommandField ShowInsertButton="true" />
Use the following code on the event OnRowDataBound to eliminate the need for
the SELECT command field and save yourself some valuable space.
Here is the HTML to create a GridView, I'm displaying a list of people, and the key
I got a solution for paging issue. ie binding of the data has to be done with the
gridview. in the page index changing method.
Protected Sub gvEmp_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvEmp.PageIndexChanging
gvEmp.PageIndex = e.NewPageIndex
gvEmp.DataBind()
End Sub
Hope this helps most of us.
21/Apr/2009 20:22 PM
SuikerSays: said:
Hey smart thinking!
I also liked cxspan's approach!
Way to go! guys!
18/May/2009 20:47 PM
Cenk Taylan Düz said: protected override void Render(System.Web.UI.HtmlTextWriter writer)
do not add AutoGenerateSelectButton="true" in <asp:Gridview> Section...
25/Sep/2009 09:17 AM
Lawty said:
Having searching for ages, reading countless blogs why the SelectedIndexChanged
event was refusing to trigger on my GridView - trying several suggestions and
failing - finally I found the comment left by cxspan - and it works. You are a
genius!!!
21/Oct/2009 12:13 PM
ASMGX said:
Thanks cxspan
your code works
14/Dec/2009 07:35 AM
srishti said:
On Clicking hyperlink in gridview and i want to pass some value to the next page
how to pass the selected row cell value to next page...
01/Apr/2010 13:48 PM
Hrushikesh/ India said:
This is great. Thanks a lot.
15/Apr/2010 13:19 PM
vegeta said:
hi paul
im using a master page which includes a search panel.when i search an employee i used to show all the employees in gridview and i can select the employee by clikin on gridview row.when i clik on gridview row im creating a session variable of that employee's ID.
but im not gettin that session var in content page bcuz content page loads first.im
gettin that session var on second page-load. how to resolv this issue.
i tried to access session var by including that search functionality into webform but still im getting the same scene(i.e im gettin the session var at second postback) Please help.......
05/May/2010 13:49 PM
said:
please if u can mail me at this id [email protected] ill be very thankfull...
05/May/2010 13:59 PM
wizzle said:
im using this code and it works fine when the panel the gridview is contained in is
set to enabled. but when the panel is disabled i get the validation error. how can i
set this so you can only select when the panel is enabled without disabled the
validation?
06/May/2010 15:55 PM
Enrique said:
Gracias por la enorme ayuda!!!
thanks a lot!.
15/Jul/2010 03:31 AM
bhasker said:
pl resolve my problem. i am getting following error while using your above code...
Invalid postback or callback argument. Event validation is enabled using <pages
enableEventValidation="true"/> in configuration or <%@ Page
EnableEventValidation="true" %> 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.
08/Sep/2010 08:12 AM
animalistix said:
this is really cool helped me alot. thanks
19/Oct/2010 15:51 PM
MCinDaBurgh said:
Thanks for the post.
I am doing something similar in vb.net and I have the row click functionality working
but realize now instead I need to only do this for an imageButton (expand/collapse).
do you know how to do this?
Specifically I need to know about the clientID syntax.Ex, i am trying to do something
Hola a todos, tengo un GridView y necesito que cuando haga click sobre una fila, la misma desencadena un evento. Para ello estoy usando el siguiente código, aunque
Alguna ayudita ¿?, saludos a todos y un fuerte abrazo para Leandro.
o Responder
o Citar
Todas las respuestas martes, 04 de mayo de 2010 15:52
becavas
85 Points
0
hola, cuando tu seleccionas una fila del gridview se desencadena el evento "SelectedIndexChanged" no el "RowDataBound", este ultimo se desencadena cuando una fila de datos se enlaza a los datos de un control GridView, la pregunta seria cual quieres desencadenar y dentro de que evento lo quieres hacer.Por otro lado no me queda muy claro lo que quieres hacer, sería bueno que expliques porque quieres invocar un evento desde otro, quiza haya mejores alternativas que eso
desarrollador .NET
o Responder
o Citar martes, 04 de mayo de 2010 16:02
Spaikers
70 Points
0
Te comento, lo que quiere realizar es algo similar a lo siguiente:
El problema es que dicha librería es de pago (aunque hay formas de conseguirla y todos sabemos cuales), y lo que deseo hacer es que cuando pulse sobre un row, esta envíe determinados datos o simplemente desencadene un evento que yo cree.
Me he dado cuenta que cuando pulso sobre una fila con el código anterior, en el "SelectedIndexChanged" no hace nada ya que tengo insertado un punto de interrupción y no se detiene porque simplemente no se ejecuta.
o Responder
o Citar martes, 04 de mayo de 2010 16:11
becavas
85 Points
0
por lo que puedo ver tu gridview no tiene ninguna columna, estas llenandola con datos?
He activado la opción AutoGenerateSelectButton y me aparece la columna con la opción "Seleccionar" pero no me sirve, ya que lo que quiero es que sin que se vea "Seleccionar" sí se pueda seleccionar una fila.
<AlternatingRowStyle CssClass="FilaAlternaGridView"></AlternatingRowStyle> </cc1:Ctrl_GridView>como veras en la parte qeu te pongo con negrita es un codigo de la base de datos de acuerdo a este codigo filtro y luego desencadeno el evento como vetas auqi es ecencial el eval
la parte de acciones es donde te mostrara una manito para que hagas click y se desencadene el ejemplo
lo QUE ESTOY HACIENDO ES PASAR EL CODIGO QUE TIENE LA GRILLA A UNA PAGINA XXX
//Agrego el link para edición de registro a la columna "Acciones" (primera columna) HyperLink lnk_Editar = new HyperLink();
lnk_Editar.Text = "Editar"; lnk_Editar.ImageUrl = "~/Iconos/Editar.png";//ESTA LINEA SOLO CARGA UNA IMAGEN NO ES OBLIGATORIA lnk_Editar.ToolTip = "Editar";
lo primero que tenes que hacer para seleccionar una fila de una grilla es lo siguiente:
1 colocas la grilla en la pagina
2 Busca en la propiedades de la grilla y pones el autogenerateselect en true
3 Mediante un procedimiento almacenado traes los datos que queres que salgan en la grilla
4 haces doble click en la grilla y pones esto:
Protected Sub GRDgrilla_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GRDgrilla.SelectedIndexChanged 'creo una fila y le agrego los datos correspondientes y luego los buelco en los txt correspondiente Dim Row As GridViewRow = GRDgrilla.SelectedRow Dim celId As Integer = Convert.ToInt32(Row.Cells(1).Text) Dim celNom As String = Row.Cells(2).Text Dim celApe As String = Row.Cells(3).Text Dim celDir As String = Row.Cells(4).Text Dim celNum As Integer = Convert.ToInt32(Row.Cells(5).Text) Dim celDni As Integer = Convert.ToInt32(Row.Cells(6).Text) Dim celTel As String = Row.Cells(7).Text Dim celEmail As String = Row.Cells(8).Text Dim celFechaNAc As DateTime = Row.Cells(9).Text Dim celFechaIng As DateTime = Row.Cells(10).Text Dim celNomUsu As String = Row.Cells(11).Text Dim celContra As String = Row.Cells(12).Text Dim celIdcat As Integer = Convert.ToInt32(Row.Cells(13).Text) Dim celRol As Integer = Convert.ToInt32(Row.Cells(14).Text) Dim celActivo As Integer = Convert.ToInt32(Row.Cells(15).Text) Dim Dt As DataTable = New DataTable("miTable") Dim cel1 As New DataColumn("Id_empleado", GetType(Integer)) Dim cel2 As New DataColumn("Nombre", GetType(String)) Dim cel3 As New DataColumn("Apellido", GetType(String)) Dim cel4 As New DataColumn("Direccion", GetType(String)) Dim cel5 As New DataColumn("Numero", GetType(Integer)) Dim cel6 As New DataColumn("Dni", GetType(Integer)) Dim cel7 As New DataColumn("Telefono", GetType(String)) Dim cel8 As New DataColumn("Email", GetType(String)) Dim cel9 As New DataColumn("Fecha_nacimiento", GetType(DateTime)) Dim cel10 As New DataColumn("Fecha_ingreso", GetType(DateTime)) Dim cel11 As New DataColumn("Nombre_usuario", GetType(String)) Dim cel12 As New DataColumn("Contraseña", GetType(String)) Dim cel13 As New DataColumn("Id_categoria", GetType(Integer)) Dim cel14 As New DataColumn("Rol", GetType(Integer)) Dim cel15 As New DataColumn("Activo", GetType(Integer))
5 Buscas el eento dataBound_row de la grilla y pones esto, esto hace que se larque la grilla seleccionada y que puedas hacer click en cualkier parte de la fila sin importatr si precionas el seleccionar o no:
Protected Sub GRDgrilla_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GRDgrilla.RowDataBound If e.Row.RowType = DataControlRowType.Pager Then 'bla bla bla ElseIf e.Row.RowType = DataControlRowType.DataRow Then 'APLICA ESTILOS A EVENTOS ON MOUSE OVER Y OUT e.Row.Attributes.Add("OnMouseOver", "Resaltar_On(this);") e.Row.Attributes.Add("OnMouseOut", "Resaltar_Off(this);") 'este es el atributio que hace marcar la fila
e.Row.Attributes("OnClick") = Page.ClientScript.GetPostBackClientHyperlink(Me.GRDgrilla, "Select$" + e.Row.RowIndex.ToString) End If End Sub
6 en la parte del codigo dentro del head y abajo del titulo pones esto: