Anda di halaman 1dari 45

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 %>" 22: SelectCommand="SELECT [EmployeeID], [FirstName], [City], 23: [Country] FROM [Employees]"> 24: </asp:SqlDataSource> 25: </ContentTemplate> 26: </asp:UpdatePanel>

Write code mentioned below in RowDataBound Event. C# 01protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 02 { 03 if (e.Row.RowType == DataControlRowType.DataRow) 04 { 05 e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';"; 06 e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; 07 08 e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex); 09 } 10 } 11 12protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) 13 { 14 GridView1.SelectedIndex = -1; 15 } VB.NET 01Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) 02 If e.Row.RowType = DataControlRowType.DataRow Then 03 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 If 08End Sub 09 10Protected Sub GridView1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) 11 GridView1.SelectedIndex = -1 12End 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: 2: 3:

<style> .visibility {Display : none} </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: 2:
Method 2.

<asp:CommandField ShowSelectButton="True" ItemStyle-CssClass="visibility"/>

Remove the code from RowDataBound Event of GridView and OverRide Render event of page, set the last parameter (bool registerForEventValidation) of ClientScript to true. C# 01protected override void Render(System.Web.UI.HtmlTextWriter textWriter) 02 { 03 foreach (GridViewRow gvRow in GridView1.Rows) 04 { 05 if (gvRow.RowType == DataControlRowType.DataRow) 06 { 07 gvRow.Attributes["onmouseover"] = 08 "this.style.cursor='hand';"; 09 gvRow.Attributes["onmouseout"] = 10 "this.style.textDecoration='none';"; 11 gvRow.Attributes["onclick"] = 12 ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + gvRow.RowIndex, true); 13 } 14 } 15 base.Render(textWriter); 16 } VB 01Protected Overrides Sub Render(textWriter As System.Web.UI.HtmlTextWriter) 02 For Each gvRow As GridViewRow In GridView1.Rows 03 If gvRow.RowType = DataControlRowType.DataRow Then 04 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 If 08 Next 09 MyBase.Render(textWriter) 10End Sub

ASP.NET: Selecting a Row in a GridView


Posted 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>; Debug.WriteLine(customerList[Convert.ToInt32(e.CommandArgument)].LastName); } } 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. CustomerGridView.RowCommand += CustomerGridView_RowCommand; In VB: 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. Enjoy!

GridView.SelectedRow Property
.NET Framework 4.5
Other Versions

0 out of 4 rated this helpful - Rate this topic Gets a reference to a GridViewRow object that represents the selected row in the control. Namespace: System.Web.UI.WebControls Assembly: System.Web (in System.Web.dll)

Syntax
C# C++ F# VB

[BrowsableAttribute(false)] public virtual GridViewRow SelectedRow { get; }

Property Value
Type: System.Web.UI.WebControls.GridViewRow A GridViewRow that represents the selected row in the control.

Remarks
When a row is selected in a GridView control, use the SelectedRow property to retrieve the GridViewRow object that represents that row.

Note

This is the same as retrieving the GridViewRow object at the index specified by the SelectedIndex prope
This object can then be used to access the properties of the selected row.

Examples
The following example demonstrates how to use the SelectedRow property to access the properties of the GridViewRow object that represents the selected row in theGridView control. C# VB

<%@ Page language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e) { // 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 + "."; } void CustomersGridView_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e) { // 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") { e.Cancel = true; MessageLabel.Text = "You cannot select " + row.Cells[2].Text + "."; } } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>GridView Select Example</title> </head> <body> <form id="form1" runat="server"> <h3>GridView Select Example</h3> <asp:gridview id="CustomersGridView" datasourceid="CustomersSource" autogeneratecolumns="False" autogenerateselectbutton="True" allowpaging="True" selectedindex="1" onselectedindexchanged="CustomersGridView_SelectedIndexChanged" onselectedindexchanging="CustomersGridView_SelectedIndexChanging" runat="server" DataKeyNames="CustomerID"> <Columns> <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" InsertVisible="False" ReadOnly="True" SortExpression="CustomerID" /> <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />

<asp:BoundField DataField="MiddleName" HeaderText="MiddleName" SortExpression="MiddleName" /> <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" /> <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" /> </Columns> <selectedrowstyle backcolor="LightCyan" forecolor="DarkBlue" font-bold="true"/> </asp:gridview> <br/> <asp:label id="MessageLabel" forecolor="Red" runat="server"/> <!-- 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 for each record is thePERSON_ID. <asp:GridView ID="PeopleGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="PERSON_ID" DataSourceID="PeopleDataObject" Width="200px" OnRowDataBound="PeopleGridView_RowDataBound" AllowPaging="True"> <Columns> <asp:BoundField DataField="USER_NAME" HeaderText="Name" SortExpression="USER_NAME" > </asp:BoundField> </Columns> </asp:GridView> The key event to note is the OnRowDataBound, use the following code to create SELECT functionality on the row. protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventAr gs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textD ecoration='underline';"; e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.Pe opleGridView, "Select$" + e.Row.RowIndex); } } Each row will then behave like a link, and when you select one it can drive the behavior of another control(s) on your page, possibly a DetailsView allowing you to INSERT a complete record to the database.

Author Paul Marshall

A self confessed Microsoft bigot, Paul loves all Microsoft products with a particular fondness for SQL Server. Paul is currently focusing on Web 2.0 patterns and practices and is always looking for better ways of doing things. I love the .net platform, and I find it to be the most productive toolset I have used to date.

Comments
Anonymous said:
This only seems to work in framework 2.0 if you add enableEventValidation="false" to the page directive in web.config, which is not recommended 18/Aug/2006 09:17 AM

Paul Marshall said:


In response to the comment regarding enableEventValidation being set to false. You don't need to do that, I've gone back to my implemention of this and its set to true in both the page and the web.config I have never used this in previous versions of the framework and this example was lifted from a .net 2.0 project. Happy coding.....

20/Aug/2006 14:22 PM

Edgar said:
Sadly I found the enableEventValidation issue too. Any suggestions?. Thx 22/Aug/2006 18:22 PM

Paul Marshall said:


I'd suggest that you look that the data in your GridView, and the other controls on your page. You will probably have data that is upsetting your viewstate. e.g. HTML code in a text box. What is the error message you're getting? 23/Aug/2006 14:52 PM

said:
I have the same problem when I click on the row on the gridview I get the enablepagevalidation = true error. If I have a select field visable on the gridview then it works ok when clicked. If I remove this it does not and it willnot fire the SelectedIndexChanged event on the gridview Please can you help 29/Aug/2006 14:16 PM

Khalegh Ahmadi, Khalegh@GMail.com said:


You can solve the invalidation problem very easy : Use the select CommandField and set it's visible property to true. Then set the Display Style of Both the Item Style and Header Style to none. Set the ItemStyle-CssClass and HeaderStyle-CssClass properties to a class created in a StyleSheet File which contains the Dispaly Style. For Example : .HideButton {Display : none} and in Gridview add the Select CommandField : <asp:CommandField SelectText ="Select" ShowSelectButton="true" ItemStyle-CssClass = "HideButton" HeaderStyle-CssClass ="HideButton" /> 30/Aug/2006 09:21 AM

Khalegh said:
You can solve the event invalidation problem very easy : Create a StyleSheet File and write the following class in it : .HideButton { Display : none} Then Use the Select CommandField and set it's Visible property to true and set both the ItemStyle-CssClass and HeaderStyle-CssClass to HideButton : <asp:CommandField SelectText ="Select" ShowSelectButton="true" ItemStyle-CssClass = "HideButton" HeaderStyle-CssClass ="HideButton" /> 30/Aug/2006 09:35 AM

Anup Garg said:


It really worked for me after making changes in config. Thanx. 31/Aug/2006 20:03 PM

Levi said:
I want to select row in the gridview only when the GridView.Enabled is true. Is there any solution? 17/Sep/2006 11:33 AM

Levi said:
Thank You, I found the solution. "if (GridView1.Enabled) Select$" + e.Row.RowIndex); 17/Sep/2006 11:45 AM

Anonymous said:
I love the solution, thanks. One issue with it though. Currently if I select one, on a Paged Gridview (allow paging), if I switch pages, the selection is moved to the current page at the same index in the page. How can this be changed to clear the selection when I switch pages? 05/Dec/2006 20:45 PM

Manuj said:
Thanks It works Good with GridView in framework2.0 25/Dec/2006 05:26 AM

Gagan said:
Thanks Paul. It is exact what i was looking for. 28/Dec/2006 16:04 PM

YK said:
GridView settings: EnabledViewState = false

LinkButton set as CommandName=Select SelectedIndexChanged event is not fired which take me to other page. When I set EnableViewState = true, it works fine. Any suggestions 16/Jan/2007 21:45 PM

mary said:
hi tried this example but i am getting the follwing error just tell me how to clear it 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. 18/Jan/2007 07:24 AM

yrksundeep said:
can some one help me how to bind the details view by selecting a row using rowdatabound event in a grid view. i need the contiuation for this code. 23/Feb/2007 07:59 AM

darshan said:
i tried but i m getting the following erro so plz give me solution and how to post back to new page record as per that record selection 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. 02/Mar/2007 06:57 AM

said:

For those that are getting the validation issue, I have solved it in my project by adding the following (be sure to replace the "GridViewControlName" with your own: Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter) 'The following line of code is required when doing a manual postback from client script. Page.ClientScript.RegisterForEventValidation(GridViewControlNa me.UniqueID)

MyBase.Render(writer) End Sub 26/Apr/2007 21:24 PM

DR said:
The mouseover doesn't work in FF. I can get the same effect with styles. 02/May/2007 01:41 AM

kenyu said:
thanks Paul,it does work for me. 02/May/2007 07:34 AM

owen said:
very usefull. thanks 03/May/2007 19:02 PM

michel said:
Any1 any idea how to set the row background to another color onmouseover? Just adding this.style.background-color:gray; doesn't work 09/Jun/2007 15:10 PM

Joey J. Barrett said:


Perfect solution thank you. What I did: The GridView is in a UpdatePanel and each selection is stored in a session allowing the user to make multiple selections then act on them.

21/Jun/2007 20:35 PM

lis716 said:
i'm using visual basic and the codes seems not to work at all. do i have to declare it ? like for example this code e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';"; the "e" needs a declaration. and the format of the code like the parethesis forst before the if does not work too...

pls help! 22/Jun/2007 03:28 AM

Aladdin said:
Thanks Paul and Khalegh - it works perfectly well using both your codes. 22/Jul/2007 07:18 AM

vishal said:
thanks for the solution, but i am getting a wierd behaviour , for paging enabled in the grid, after i go to next page, i get the same data on the previous ( first ) page ( from dataset ) on clicking on a row on second/next page.. 26/Jul/2007 08:00 AM

yamini said:
it is nice 18/Sep/2007 11:07 AM

KathyPDX said:
That is so cool! Works great, thanks. 01/Oct/2007 23:56 PM

ousama said:
hello paul,

i just one question and i hope you could help me because i have been surfing the net for a week and i could not find the answer. when my application goes from one page to another based on a selected row in my grid i want ,when i click on the back button, to see the selected already kept selected in the privouse table. i hope it is clear for you thanks in advanced 23/Nov/2007 22:22 PM

Ryan said:
The VB version of this code: Protected Sub YourGridName_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) If (e.Row.RowType = DataControlRowType.DataRow) Then e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand';this.style.textDecoration='underline';") e.Row.Attributes.Add("onmouseout", "this.style.textDecoration='none';")

e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(Me.YourGridName, "Select$" + e.Row.RowIndex.ToString())) End If End Sub Note here that I'm not using a handler for this function. If you do this funciton gets called twice every time you click a row - once from the OnRowDataBound property in the gridview, and the other from the handler. To get this to work if you are getting the " Event validation is enabled using..... " error, I reccommend using Khalegh Ahmadi's hack. I have tried it and it works beautifully. The way I understand it is he tricks server into thinking that postback came from the server control. A few things to note with his hack is that if you haven't already, you need to add a link to the stylesheet you are going to use up the top of your aspx page between the <head> </head> tags, something like: <link rel="Stylesheet" href="stylesheet.css" type="text/css" /> 04/Dec/2007 01:43 AM

trycatchscenario said:

Ok I found a easier solution for those who just want to disable it for the page rather the the config file for the whole project. On the top of the .aspx page add this line <%@ Page EnableEventValidation="false" %> 19/Dec/2007 22:14 PM

said:
What if the gridview have a deletebutton column which does not want to bahave like a link ? 04/Jan/2008 11:15 AM

marshp3 said:
You could set the button to not "bubble" the event to the row. Skype me or Google to find out how to do it 04/Jan/2008 14:48 PM

Ranch said:
Thanks Paul! Very nice Code! 11/Jan/2008 14:54 PM

cxspan said:
The guy who posted (and didn't leave a name) on April 26, 2007 - 9:24 PM was on the right track. You need to override the Render function and add the onclick/styling code here. Remove this code from the RowDataBound function and DO NOT DISABLE EVENT VALIDATION! protected override void Render(System.Web.UI.HtmlTextWriter writer) { AddRowSelectToGridView(GridView1); AddRowSelectToGridView(GridView2); AddRowSelectToGridView(GridView3); base.Render(writer); } private void AddRowSelectToGridView(GridView gv) {

foreach (GridViewRow row in gv.Rows) { row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';"; row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gv, "Select$" + row.RowIndex.ToString(), true)); } } 31/Jan/2008 19:04 PM

Nev said:
Thanks Paul,,really work wonders. did'nt know of this feature in the fridview..Excellent!! 02/Feb/2008 12:24 PM

Nev said:
Excellent work Paul!! 02/Feb/2008 12:26 PM

ahm said:
i need to display in textboxes when i click a particular row in gridview by using asp.net using vb.net 12/Feb/2008 13:56 PM

Tarun said:
All soutions works fine so long as you dont have any other command like delete, edit in the gridview. if you have it, then if you click delete, first select and then delete command will be fired, resulting two postbacks. i am curious if someone posts a solution for this 07/Mar/2008 11:08 AM

dipak sanki said:


when i click a particular row in gridview,i need to display another gridview by using asp.net using C# 12/Mar/2008 10:36 AM

amanda said:
hi. the code work great, thanks!! i was also wondering what extra steps/codes necessay it make the clicked item redirect to another page and at the same time extracting its value. any tips would help thanks again. 03/Apr/2008 12:10 PM

sushanth said:
hey...it works great, only put.. the EnableEventvalidation="false" in the .aspx page.. it works fine. this is my entire .cs code file : public partial class Default3 : System.Web.UI.Page { static string connection = System.Configuration.ConfigurationManager.ConnectionStrings["EhrmConne ctionString"].ToString(); SqlConnection con = new SqlConnection(connection); protected void Page_Load(object sender, EventArgs e) {

con.Open(); try {

SqlCommand cmd1 = new SqlCommand("select * from Admin_HRMS_Grade", con); SqlDataAdapter adp = new SqlDataAdapter(cmd1); DataSet ds = new DataSet(); adp.Fill(ds, "Admin_HRMS_Grade");

GridView1.DataSource = ds; GridView1.DataBind();

} catch (Exception ce) {

Response.Write(ce.Message + ce.StackTrace); } finally { con.Close();

protected void Gridview1_page(object sender, System .Web .UI .WebControls .GridViewPageEventArgs e) {

GridView1.PageIndex = e.NewPageIndex; GridView1.DataBind(); } protected void Submit1_ServerClick(object sender, EventArgs e)

try { con.Open();

SqlCommand cmd = new SqlCommand("Admin_HRMS_Grade_Insert", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Grade_name", Text2.Value); cmd.Parameters.AddWithValue("@Grade_desc", TEXTAREA1.Value); cmd.Parameters.AddWithValue("@Grade_band", Text3.Value);

if (Radio1.Checked == true) { cmd.Parameters.AddWithValue("@Status",1); } else if (Radio2.Checked == true) { cmd.Parameters.AddWithValue("@Status",0); }

cmd.ExecuteNonQuery(); } catch (Exception ce) { Response.Write(ce.Message + ce.StackTrace); } finally { con.Close(); }

} protected void Button1_Click(object sender, EventArgs e) {

try { con.Open(); SqlCommand cmd2= new SqlCommand("select * from Admin_HRMS_Grade where Grade_Name='"+Text1.Value+"'", con); SqlDataAdapter adp2 = new SqlDataAdapter(cmd2); DataSet ds2 = new DataSet(); adp2.Fill(ds2, "Admin_HRMS_Grade"); GridView1.DataSource = ds2; GridView1.DataBind();

} catch { } finally { con.Close(); } } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { try { string a;

con.Open(); GridViewRow row = GridView1.SelectedRow;

//Text1.Value = row.Cells[1].Text; Text1.Value = GridView1.SelectedRow.Cells[1].Text;

a = Text1.Value; } catch { } finally { }

protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { try { GridViewRow row = GridView1.Rows[e.NewSelectedIndex]; } catch { } finally { } }

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) {

e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';this.s tyle.backColor='Red'"; e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex); } } } 17/Apr/2008 10:46 AM

deive said:
Thanks cxspan - that was exactlly what was needed

28/May/2008 19:10 PM

Lawrence said:
Hi, How about this? protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "MySelect") { GridViewRow mySelectedRow = ((GridViewRow)(((DataControlFieldCell)(((WebControl) (e.CommandSource)).Parent)).Parent)); int mySelectedRowIndex = mySelectedRow.RowIndex; } } In your source code: ASPX: ........ <asp:TemplateField ShowHeader="False"> <ItemTemplate>

<asp:LinkButton ID="lnkMySelect" runat="server" Text="MySelect" CausesValidation="False" CommandName="MySelect" /> </ItemTemplate> </asp:TemplateField> .......... This would allow you to have access to the GridViewRow of the clicked link. Hope this helps! 14/Jul/2008 19:16 PM

Alex said:
Hi there. I get an error saying: The name 'ClientScript' does not exist in the current context any help would be greatly appreciated 16/Sep/2008 06:38 AM

WildCow said:
For Alex: Page.ClientScript (I had to search for that one too...). For me: I can't get the mouse icon to change in FireFox, only in IE. Anyone succeeded? 14/Oct/2008 05:49 AM

Pheno said:
@WildCow You have to use this.style.cursor='pointer'; 22/Oct/2008 09:59 AM

JohnJacob said:
@Alex: Try using this.style.cursor='pointer' instead of this.style.cursor='hand' 22/Oct/2008 20:15 PM

ST said:
Thanks paul your information on the on click it helped me. Now I have another question I am trying to add a line to an existing gridview I click on a line and would like to add a line under the line I clicked on. Thanks 04/Nov/2008 12:10 PM

Harrison said:
Thank you so much guys for all your contribution. I have gotten the completed the skeletal work. but this is work I'm having problems How can you access to the index of the Row that's been selected? I only allowing it to select one item at a time. Thank you so much guys! 18/Feb/2009 15:42 PM

David said:
I ran across this and some other posts that proposed the same basic approach, however I ended up getting an error message related to Validation being set to true. (I don't recall the exact wording of it.) As an alternative, I adapted the solution slightly to to hard code the 'javascript:_doPostBack()' into a string using the same variables to create the proper references. The result is that the onClick is generated with the Page.ClientScript.GetPostBackEventReference(). Sub gridView_ShowList_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Dim functionName As String 'Note that the gridview name is hard coded, the original code uses the sender object, but I couldn't get it to work 'in concatenating the string functionName = "javascript:_doPostBack('gridViewShowList'" "," "'" "Select$" & e.Row.RowIndex.ToString "')" If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Attributes.Add("onclick", functionName)

End If End Sub http://www.aspmessageboard.com/showthread.php?t=230982 27/Feb/2009 02:50 AM

nikki said:
Thanks. It helped me alot. 02/Apr/2009 19:38 PM

mmogan said:
Hi Paul, thanks for the solution, but i am getting a problem, for paging enabled in the grid, after i go to next page, i get the same data on the previous ( first ) page ( from dataset ) on clicking on a row on second/next page...Please help me with a solution 21/Apr/2009 16:43 PM

mmogan said:
Hi folks, 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 Dz said:


protected override void Render(System.Web.UI.HtmlTextWriter writer) {

AddRowSelectToGridView(GridView1); base.Render(writer); }

private void AddRowSelectToGridView(GridView gv) { if (gv.EditIndex == -1) { foreach (GridViewRow row in gv.Rows) { row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';"; row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gv, "Select$" + row.RowIndex.ToString(), true)); } } } A Little Change In Code if you add "(gv.EditIndex == -1)" You can Edit on gridview 30/Jun/2009 18:20 PM

Rupesh Bari said:

Thank you so much frnd...You solve my this critical problem if any one want to hide allowSelectButton then write simply in <Columns>. <asp:CommandField SelectText=" " ShowSelectButton="True" /> 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 aloklingayat@gmail.com 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 like this: Dim MyImgButton As ImageButton MyImgButton=CType(MyGridView.SelectedRow.FindControl("imgButton"), ImageButton) MyImgButton.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(MyGridView, "Select$" + MyImgButton.ClientID, True)) so I am looking for this part: "Select$" + MyImgButton.ClientID not sure what to put there, if anyone has an idea about this please let me know. thx MC 28/Oct/2010 13:11 PM

said:
I have the problem when I click on the row on the gridview I get the enablepagevalidation = true error. If I have a select field visable on the gridview then it works ok when clicked. If I remove this it does not and it willnot fire the SelectedIndexChanged event on the gridview Please can you help 18/Nov/2010 09:07 AM

Matt said:
Cheers cxspan, moving this code into the render event (where it can be registered for event validation) solved all my problems - kudos! 04/Jan/2011 14:44 PM

MarKus said:

it worked fine,

Thx

21/Feb/2011 14:17 PM

Edgardo said:
Even 4 years after being published this is still veryn helpful, save me a lot of time for a project I am working in..... Thanks Paul. 07/Mar/2011 16:14 PM

rgtidwell said:
Thanks! Works GREAT!! 14/Oct/2011 15:41 PM

varsha said:
I use in my application but it not works in mozila but the hand cursor is not display. 07/Nov/2011 05:30 AM

Name said:
Tks cxspan 23/Feb/2012 19:08 PM

jboeke said:
Upvote to cxspan! Yours really is the most elegant solution and also avoid disabling EventValidation. Cheers! 03/Sep/2012 06:28 AM

Reza said:
Hello Michel, use this.style.backgroundColor='Gray' instade of this.style.background-color:gray 05/Sep/2012 22:49 PM

Merrill Reddy said:

Page works fine after adding this parts protected override void Render(System.Web.UI.HtmlTextWriter writer) { AddRowSelectToGridView(GridView1); AddRowSelectToGridView(GridView2); AddRowSelectToGridView(GridView3); base.Render(writer); } private void AddRowSelectToGridView(GridView gv) { foreach (GridViewRow row in gv.Rows)

row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";

row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(gv, "Select$" + row.RowIndex.ToString(), true));

} }

Microsoft Developer Network > Pgina principal de foros >

Foros de Desarrollo > ASP.NET > Seleccionar una fila en GridView

Seleccionar una fila en GridView


Formular una pregunta
martes, 04 de mayo de 2010 15:12

Spaikers 70 Points

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 cdigo, aunque ando muy muy perdido ya que estoy inicindome en ASP.NET, y lo mio es en cierta medida Windows Forms. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[0].Attributes.Add("onclick", ClientScript.GetPostBackEventReference(GridView1, "Select$" + e.Row.RowIndex.ToString())); e.Row.Cells[0].Style.Add("cursor", "pointer"); } } Segn parece, dicho cdigo creo que hace que se desencadene el GridView1_SelectedIndexChanged, pero ni caso. El cdigo de la web es: <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server" onrowdatabound="GridView1_RowDataBound" onselectedindexchanged="GridView1_SelectedIndexChanged"

onrowcommand="GridView1_RowCommand"> <HeaderStyle BackColor="Beige" BorderColor="Azure" FontBold="true" /> <SelectedRowStyle BackColor="Crimson" Font-Size="Large" /> </asp:GridView> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> </ContentTemplate> </asp:UpdatePanel> </form>

Alguna ayudita ?, saludos a todos y un fuerte abrazo para Leandro.

Responder

Citar

Todas las respuestas


martes, 04 de mayo de 2010 15:52

becavas 85 Points

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, sera bueno que expliques porque quieres invocar un evento desde otro, quiza haya mejores alternativas que eso

desarrollador .NET o Responder

Citar martes, 04 de mayo de 2010 16:02

Spaikers 70 Points

Te comento, lo que quiere realizar es algo similar a lo siguiente: http://demos.devexpress.com/ASPxGridViewDemos/Rows/FocusedRow.aspx El problema es que dicha librera 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 enve determinados datos o simplemente desencadene un evento que yo cree. Me he dado cuenta que cuando pulso sobre una fila con el cdigo anterior, en el "SelectedIndexChanged" no hace nada ya que tengo insertado un punto de interrupcin y no se detiene porque simplemente no se ejecuta. o Responder

Citar martes, 04 de mayo de 2010 16:11

becavas 85 Points

por lo que puedo ver tu gridview no tiene ninguna columna, estas llenandola con datos?

desarrollador .NET o Responder

Citar martes, 04 de mayo de 2010 19:55

Spaikers 70 Points

Claro, la relleno mediante protected void Page_Load(object sender, EventArgs e) { ObtenerInformacion(); } private void ObtenerInformacion() { using (DataTable DTDatos = WebVeloty.ManipulacionDatos.GetDatos()) { GridView1.DataSource = DTDatos; GridView1.DataBind(); } } o Responder

Citar martes, 04 de mayo de 2010 20:18

Spaikers 70 Points

He activado la opcin AutoGenerateSelectButton y me aparece la columna con la opcin "Seleccionar" pero no me sirve, ya que lo que quiero es que sin que se vea "Seleccionar" s se pueda seleccionar una fila.

Saludos. o Responder

Citar martes, 04 de mayo de 2010 22:16

Pablo Gonzalez
Ecuasoftware

2.365 Points

hola.. si tienes datos puedes hacer en el evento RowDataBound mira te pongo un codigo de ejemploque yo tengo: mi gridview se llama Listado primero como debe ir en el codigo html <cc1:Ctrl_GridView ID="Listado" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" PageSize="25" OnRowDataBound="Listado_RowDataBound">

<RowStyle CssClass="FilaGridView"></RowStyle> <Columns> <asp:TemplateField HeaderText="Acciones"> </asp:TemplateField> <asp:TemplateField HeaderText="Cdigo"> <ItemTemplate> <asp:Label ID="lbl_codigo" runat="server" Text='<%# bind("codigo") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="nombre" HeaderText="Nombre" /> <asp:BoundField DataField="margen" HeaderText="Margen" /> <asp:TemplateField HeaderText="Porcentaje"> <ItemTemplate> <asp:CheckBox ID="chk_Porcentaje" runat="server" Checked='<%# Eval("porcentaje").ToString() == "1" %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Eliminado"> <ItemTemplate> <asp:CheckBox ID="chk_Eliminado" runat="server" Checked='<%# Eval("eliminado").ToString() == "1" %>' /> </ItemTemplate> </asp:TemplateField> </Columns> <PagerStyle CssClass="PaginadorGridView"></PagerStyle> <HeaderStyle CssClass="CabeceraGridView"></HeaderStyle> <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

y en tu codebehind tendras algo asi

protected void Listado_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { string Codigo = DataBinder.Eval(e.Row.DataItem, "codigo").ToString(); //Agrego el link para edicin 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"; lnk_Editar.NavigateUrl = "~/Modulos/Bodega/wfm_Mant_Tipoprecio.aspx" + EncriptarQueryString("Codigo=" + Codigo); e.Row.Cells[0].Controls.Add(lnk_Editar); } } cualquier duda comenta..

Pablo Gonzlez Desarrollo de Sistemas. Ecuasoftware.Net Ecuador. o Responder

Citar martes, 04 de mayo de 2010 23:06

yoguille 50 Points

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("Contrasea", 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))

Dt.Columns.Add(cel1) Dt.Columns.Add(cel2) Dt.Columns.Add(cel3) Dt.Columns.Add(cel4) Dt.Columns.Add(cel5) Dt.Columns.Add(cel6) Dt.Columns.Add(cel7) Dt.Columns.Add(cel8) Dt.Columns.Add(cel9) Dt.Columns.Add(cel10) Dt.Columns.Add(cel11) Dt.Columns.Add(cel12) Dt.Columns.Add(cel13) Dt.Columns.Add(cel14) Dt.Columns.Add(cel15)

Dim Rw As DataRow = Dt.NewRow() Rw("Id_empleado") = celId Rw("Nombre") = celNom Rw("Apellido") = celApe Rw("Direccion") = celDir Rw("Numero") = celNum Rw("Dni") = celDni Rw("Telefono") = celTel Rw("Email") = celEmail Rw("Fecha_nacimiento") = celFechaNAc Rw("Fecha_ingreso") = celFechaIng Rw("Nombre_usuario") = celNomUsu Rw("Contrasea") = celContra Rw("Id_categoria") = celIdcat Rw("Rol") = celRol Rw("Activo") = celActivo Dt.Rows.Add(Rw) GRDgrilla.DataSource = Dt GRDgrilla.DataBind() End Sub 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: <script type="text/javascript"> function Resaltar_On(GridView) { if(GridView != null) { GridView.originalBgColor = GridView.style.backgroundColor; GridView.style.backgroundColor="#FF0000"; } }

function Resaltar_Off(GridView) { if(GridView != null) { GridView.style.backgroundColor = GridView.originalBgColor; } } </script> que va a hacer esto es que se activen las funciones onmouseout y onmouseovert marcando cada fila a medida que el mouse pasa por la grilla. Espero que te sirva

o o o

Propuesto como respuesta yoguille martes, 06 de julio de 2010 21:38

Responder

Citar mircoles, 05 de mayo de 2010 12:19

Spaikers 70 Points

El siguiente cdigo funciona sin problemas pero siempre necesita el AutoGenerateSelectButto.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //Funciona si esta la columna Seleccionar if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';"; e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink( GridView1,

String.Concat("Select$", e.Row.RowIndex.ToString())); e.Row.Style.Add("cursor", "pointer"); } }

La opcin que me queda es esta otra y veo que s funciona

protected override void Render(HtmlTextWriter writer) { const string onMouseOverStyle = "this.className='GridViewMouseOver';"; const string onMouseOutStyle = "this.className='{0}';"; foreach (GridViewRow gvr in GridView1.Rows) { gvr.Attributes["onmouseover"] = onMouseOverStyle; gvr.Attributes["onmouseout"] = String.Format( onMouseOutStyle, this.GetRowStyleCssClass(gvr.RowState)); gvr.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink( GridView1, String.Concat("Select$", gvr.RowIndex), true); } base.Render(writer); } private string GetRowStyleCssClass(DataControlRowState state) { if ((state & DataControlRowState.Edit) > 0) { return GridView1.EditRowStyle.CssClass; } else if ((state & DataControlRowState.Selected) > 0) { return GridView1.SelectedRowStyle.CssClass; } else if ((state & DataControlRowState.Alternate) > 0) { return GridView1.AlternatingRowStyle.CssClass; } else { return GridView1.RowStyle.CssClass; } } o o o
Marcado como respuesta Spaikers jueves, 06 de mayo de 2010 12:41

Responder

Citar

Anda mungkin juga menyukai