Gridview Hyperlink Select Row & State on Row?

I have a gridview that has a hyperlink in it that I use to create querystring to filter a second gridview on the same page.  Is it possible for the hyperlink to select the row that you click on and then stay on that row when it reloads?  Right now when I click on it it resets the gridview state and of course doesn't select the row. I've tried a few of the hacks but I couldn't get any to work.  Here is the gridview and the code I've tried

Gridview Source

1        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
2        {
3            if (e.Row.RowType == DataControlRowType.DataRow)
4            {
5                e.Row.Attributes.Add("onMouseOver", "'hand';");
6                e.Row.Attributes.Add("onClick", Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Select$" + e.Row.RowIndex.ToString()));
7            }
8        }
9        protected override void Render(HtmlTextWriter htmlTextW)
10       {
11           // .NET will refuse to accept "unknown" postbacks for security reasons. Because of this we have to register all possible callbacks
12           // This must be done in Render, hence the override
13           for (int i = 0; i < GridView1.Rows.Count; i++)
14           {
15               Page.ClientScript.RegisterForEventValidation(new System.Web.UI.PostBackOptions(GridView1, "Select$" + i.ToString()));
16           }
17           // Do the standard rendering stuff
18           base.Render(htmlTextW);
19       }
20       protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
21       {
22           if (e.Row.DataItemIndex == -1)
23               return;
24           e.Row.Attributes.Add("onMouseOver",
25             "'hand';");
26           e.Row.Attributes.Add("onclick", this.GetPostBackClientEvent(GridView1, "Select$" + e.Row.RowIndex.ToString()));
27       }
28       protected override void Render(HtmlTextWriter writer)
29       {
30           foreach (GridViewRow row in GridView1.Rows)
31           {
32               row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(GridView1, "Select$" + row.RowIndex.ToString(), true));
33           }
34           base.Render(writer);
35       }
10/23/2008 7:41:32 PM 72751 articles. 3 followers. Follow

8 Replies

Similar Articles

[PageSpeed] 55

Assuming that you haven't disabled the ViewState, have you tired setting the GridView's SelectedIndex?  If you have ViewState active on the control, it should persist between postbacks.

Failure is always an option. Avoid situations where it is the only option.
10/23/2008 10:53:26 PM

 I haven't disabled anything unless it is by default, but how does a hyperlink make it "Select" the current row when I is navigating away? Are you saying that the way it is now should work without any hard coding the select row event?  I'm a begginer so not quite sure how to "set the Gridview's SelectedIndex".  I'll research that a bit.

10/24/2008 12:34:38 AM

Start with this:

Go to the GridView Tasks on the top right corner of the gridview (where you can select the datasource) in design mode.  Choose to Edit Columns.  Look at the Command Fields.  There is a Select column you can add.  Do that and observe the result.  Go back in and change that column to a template field (bottom rigth side of the Edit Columns form). 

Go back to the GridView Tasks and edit templates, and choose the item template for the column.  You will notice a link button.  You can either add a handler for the click or command events if you want to do something servers, or setup the OnClientClick to do something server side.  

The key is the CommandName property, "Select", which GridView is designed to handle by setting the SelectedIndex property to the index of the row in which the Link Button appears.  If one wants they could do the same in a click or command event handler, but why go through the effort if you don't need to. 

Failure is always an option. Avoid situations where it is the only option.
10/24/2008 4:48:43 AM

 Sounds like what I need, thanks for the help.  Just weird how you have to convert a select field to a template field instead of just dumping a template field in there to begin with which sounds like the right way but hey I have to think like MS.

10/25/2008 5:13:17 PM

Actually, you can add any sort of button in there and set its CommandName field to "Select" and it will work.  The advantage of using the "packaged" version is that it follows any formatting you do to it, versus having to manually apply it.

Failure is always an option. Avoid situations where it is the only option.
10/25/2008 6:46:59 PM

  I found my problem, it's because I'm using a querystring to filter the child gridview with a hyperlink.  I'm using it to navigate to the same page providing the querystring to filter the second gridview.  How can I do this using a command button.  There is no navigateURL property.

This is what I'm doing now

                        <asp:TemplateField HeaderText="Year">
                            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/OSFileByDate.aspx?Year=" + Eval("y") %>'><%# Eval("y") %> (<%# Eval("NoFiles") %> files)</asp:HyperLink>
                        <asp:CommandField ShowSelectButton="True" />

10/27/2008 1:03:01 PM

Hi barkster,

You can handle SelectedIndexChanging event of GridView:

protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        Response.Redirect("~/OSFileByDate.aspx?Year=" + ((DataRowView)GridView1.Rows[e.NewSelectedIndex].DataItem)["y"].ToString());


Qin Dian Tang
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.
10/28/2008 8:31:48 AM

If you are navigating back to the same page, there is no need to change destinatination (by default it will post back to itself.  You can look at the PostBackURL if it needs to go elsewhere, however).  Because your gridview is on the same page you really don't want to do a response redirect, as Qin Dian Tang suggests (at that point you might as well just use the hyper link and avoid the processing time of the event handler).  You do, however, want to do something when the select button is clicked.

Using the SelectedIndexChanged of the first gridview is one option.  Going the template route and triggering off the Command or Click events are also viable. In any case this is where you want to apply the filtering logic for your circumstances.  If the second grid view is bound to an ObjectDataSource you can set the DefaultValue property of any SelectParameters and then call databind, which should make it all work.

Failure is always an option. Avoid situations where it is the only option.
10/28/2008 2:45:51 PM

Similar Artilces:

Selecting the multiple rows in GridView and inserting the selected rows to another Gridview & Performing some operations on it
 Dear All, I have become mad for solving this problem. Please Help me. I have a Gridview bound to a datasource. I inserted the CheckBox Control in Templet to select certain rows. Gridview1 contains some products id & name.I want to insert the selected rows in to second Gridview  and in the second Gridview I need to add two more colums AdvicedQty & AcceptedQty(TextBox Cotrol).The user will select few products in Gridview1 & clicks add which will be added another gridview then in second Gridview he enters the AdviceQty & AcceptedQty.After entering the data he cli...

Add new controls to a gridview row; when editing that row using the edit row feature in the gridview control.
Hi all  I have a questions that looks hard / complex to me, and i know you can help me in this. Q {  I have row in a Gridview and i have an edit option to it. I press the edit button, to edit the values in that row and update data all the way back to the database. Now when i press the edit button, i want a drop down list to be displayed that contain values for a particular field in my grid view. (for now only plain text boxes appear.) } I hope you understand my question, all i need to do is replace the text box controls with a dropdown list when i am editing a row in ...

Selecting a gridview row and keeping the last selected row in a gridview highlighted after mouse moves over a new row.
What is the best way to show a gridview row highlighted once selected and keep it highlighted once the mouse moves over a different row? Thanks, Steve hi,you can use <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="#FFFFFF" /> plz let me know if i misunderstood you Thanks for your help. One problem; however, is that after the row has been selected and I check the "grid.SelectedIndex" it has a value of -1 and not the index of the row that was selected on the grid. What do you recommend? Thanks, Steve hi, sorry i din...

Gridview paging enabled. Has checkbox to select the row . If user select the checkbox on one page and move to 2nd page to select the rows there also to export the selected rows to excel. But doing so
HiI am using Gridview and that has paging enabled. Using checkbox to select the particular row of the gridview to export the selected rows to the excel . Everything is working fine except for one case.Let user selected the "check" box for, five rows which user would like to export to excel (two of rows on page 1 of results and 3 of them on page 2 of results), however it only exports the 3 row details from page 2, because it seems to de-select the 2 rows from page 1 when I move to page 2 and vice versa. The code i am using is as :protected void BtnExcel_Click(object sender, EventArg...

Problem in Using DropDownList Control to select a selected row of SqlDataSource that is under GridView Control
Hi all,In my SQL Server Management Studio Express, I have a database "ChemDatabase" that has a table "LabData"  formatted in the following way: SampleID int PRIMARY KEY, SampleName nvarchar(25), ChemicalName, nvarchar(25), Concentration decimal(6.2) with 5 rows of records in this .dbo table. In my Visual Web Developer Express, I created a website "RPD-TCE" for extracting a row of record from the LabData table by using a DropDownList, a GridView and a SqlDataSource.  I want to click DropDownList to list one number of S...

new row below selected row in gridview to display child gridview
Hello,   I have a gridview that up selected..shows the nested child grivdview. The problem I currently have is that it stuffs all the data into a column whcih blows the whole tbale out of whack. What I need to do is create a new row below the sleected row to house the new child grivdview. I have seen third party controls do this such as teleriks radgrid but I wont to do this with the gridview control.  Any articles on how to do this? Does AJAX support this? Any help is greatly appreciated.    ...

I want to select top 3 rows except the first from 4 rows of a Table. It should select from top 2 row,top3 row and top4 row.
 Hi, Let say I've 4 rows in a table. I want to select top 3 rows except the first from 4 rows of a Table. It should select from top 2 row,top3 row and top4 row. Thanks in advance Asghar Ali Mohammed Designer and Developer)Do not forget to "MARK AS ANSWER" on the post that helped you. If you can use Linq, you can use Skip., EdMicrosoft MVP - ASP/ASP.NET Hii dear..U can fire the Query select Top(3) from Table1 order by id desc.. "A conclusion is whe...

Using a row selection in a gridview to create database rows for another gridview
Hi there, I have 2 gridviews on a form, the first displays some template rows from a database table.  The second displays some user specific rows (with additional data added to the template info) from the same table. They both work fine for displaying the info.  Now what I want to do, is allow users to 'select' a template row on the first gridview, and have that action automatically: create a new user-specific row, with added fields from profile data etc. insert it into the table then refresh the second gridview in order to show the new added row. C...

Insert row above selected row in GridView
Hi, I've been asked to create a list with an insert button at the end of each row that, when clicked, will insert a new line above the selected row and allow the user to enter in information.  It won't be an edit, but a new entry - however it needs to be displayed above the row with the "Insert" button.  I'm not sure if this is possible or not, but any help would be most appreciated. Thanks! Check this article my suggestion helps Regards,Vinz"Code, Beer and Music" that's my way of ...

Data Controls insert rows into gridview then insert rows from gridview into SQL Table
Hello there, I'm still new at performing miracles with code . Currently I am having trouble with my latest coding adventure I have a web application which records jobs and labour assigned to jobs. The issue in particular I'm having is the way in which labour is to be assigned. I want to use standard controls (Textbox, Dropdownlist) to record the values into a gridview (ie,put multiple rows into the gridview using the controls). Then, when all the inserting is complete, the user clicks a submit button to insert all the rows from the gridview into a database table. The reason for...

GridView & OnRowUpdating & no control in a proper row
I have the following ASPX:<asp:GridView ID="ctlAllocations" runat="server" OnRowDeleting="ctlAllocations_OnRowDeleting" OnRowCommand="ctlAllocations_OnRowCommand" OnRowCancelingEdit="ctlAllocations_OnRowCancelingEdit" OnRowEditing="ctlAllocations_OnRowEditing" OnRowUpdating="ctlAllocations_OnRowUpdating" OnRowUpdated="ctlAllocations_OnRowUpdated" OnRowDataBound="ctlAllocations_OnRowDataBound" > <Columns> <asp:TemplateField HeaderText="GL Account" HeaderStyle-Horizontal...

selecting row in gridview by clicking anywhere in row (not just on 'select' link)
Hi there- I would like my gridview to behave such that a click anywhere in the (whole length of the) row would act just like clicking the "select" column link. Anyone have any code or suggestions?   You could use: ( but you would also need to disable event validation ) <%@ Page Language="VB" EnableEventValidation="false"%> Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Attributes.Add("onclick", "javascript:__doPostBack('GridView1','select$" &...

Iwant to select a row and column in gridview with select radiobutton. but No checked change event.below put a button .if click that button to seleced row values will select
I want to select a row and column in gridview using radiobutton in gridview . if which radio button is select that row will select and i want that row column values in outside individual textboxes of next page.  but in that only single radiobutton will select and no post back="true" bcz iam not using checked change property. i inserted button below gridview. if i click the that selected row and columns values are stored into textboxes of next page im using this code .but im getting one column in that row. but i want all columns in that selected row so plz repla...

select multiple rows with its row highlighted in GridView
Hello everyone, I'm not using any checkbox or select command to select the row in the GridView, I use the "RowDataBound" event in the GridView for the "onmouseover" click and row select.  That works fine for me but I want to have the functionality to select a multiple rows with its row highlighted and have a row selected count. For example, If I select a row, it hightlights that row and if I select another row, it will do the same thing and have the previous row still highlighted.  I have been looking for a way to implement this but can't find a ...

Web resources about - Gridview Hyperlink Select Row & State on Row? -

Hyperlink - Wikipedia, the free encyclopedia
A hyperlink points to a whole document or to a specific element within a document. Hypertext is text with hyperlinks. A software system for viewing ...

SA Supreme Court rules Dr Janice Duffy was defamed by Google through its hyperlinks, auto-complete and ...
A FORMER SA Health researcher has won a six-year legal battle against Google, proving she was defamed by the internet giant due to the way it ...

Banned hyperlinks could cost you $11,000 a day
The Australian communications regulator says it will fine people who hyperlink to sites on its blacklist, which continues to be controversially ...

ANALYSIS - Supreme Court hyperlink decision a victory for free speech
A hyperlink by itself should never be seen as 'publication' of other content, the Supreme Court said. But when it comes to libel the court did ...

Review: HyperLink is a great, inexpensive steel bracelet for the Apple Watch
Apple's own stainless steel link bracelet is too expensive for many of us to consider. HyperLink, however, is a less expensive alternative that ...

Apple's 'audio hyperlink' tech can control devices with inaudible sonic pulses
An Apple patent filing published by the U.S. Patent and Trademark Office on Thursday describes a method of encoding hyperlinks into an audio ...

Patent troll sending out invoices for image hyperlinks
A company named Vuestar thinks everyone who links images to pages on the Web …

How Effective Hyperlinks Can Help Your Blog
... link text explain exactly where the link is leading you or does it say something generic like click here ? When I saw Writing Effective Hyperlinks ...

Gmail's Shortcut for Inserting Hyperlinks
... doesn't mean Google shouldn't improve them. Many people complained that Gmail's rich text editor doesn't have a shortcut for inserting hyperlinks ...

Scientology loss keeps hyperlinks legal
The Church of Scientology loses a courtroom battle to compel a Dutch writer and her ISP to remove postings from a Web site, in a ruling that ...

Resources last updated: 12/21/2015 7:58:49 PM