Set Focus On Selected Row

Mar 24, 2010 at 1:49 PM

Hi I have a problem with focus on GridView. How can I set the focus on the selected row after postback? Any idea how to solve it? Thanks.

Mar 24, 2010 at 2:27 PM
vtamas wrote:

Hi I have a problem with focus on GridView. How can I set the focus on the selected row after postback? Any idea how to solve it? Thanks.

Vtam --

Your question concerned me because I need this functionality to work for my current job.

As such, I ran some tests.

Actually, tests indicate that the CoolGrid already does this intrinsically, without having to do anything special.

Please see the test code below to see this work.

As such, it appears that your situation may be different a bit-- can you describe what it is you are doing and what you want to achieve, in more detail, perhaps with a code sample?

 

This is the code-infront...

<%@ page language="C#" autoeventwireup="true" codefile="CoolGridTestPage04.aspx.cs" inherits="CoolGridTestPage04" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ register assembly="IdeaSparx.CoolControls.Web" namespace="IdeaSparx.CoolControls.Web" tagprefix="iscc" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title></title>
	<link rel="Stylesheet" href="Default.css" />
</head>
<body>
	<form id="form1" runat="server">
	<div>
		<p>
			<a href="Default.aspx">Default.aspx</a>
		</p>
		<p>
			<asp:label id="MessageLabel" runat="server"></asp:label>&nbsp;
		</p>
		<p>
			This page shows a test to demonstrate that the selected-index persists after postback.
		</p>
		<p>
			Select a row and then click on the PostBack button to see it work.
		</p>
		<p>
			<asp:button id="PostBackButton" runat="server" text="Fire A PostBack Now" />
		</p>
		<p>
			<iscc:coolgridview id="MainGridView" runat="server" autogeneratecolumns="false" allowsorting="True" height="500px" width="950px" allowpaging="false" emptydatatext="NULL" cssclass="IsccGridStyle" pagesize="1000000" enableviewstate="true" allowresizecolumn="false" onsorting="MainGridView_Sorting" fixheaders="true" >
				<boundarystyle bordercolor="Transparent" borderwidth="0px" borderstyle="None"></boundarystyle>
				<alternatingrowstyle cssclass="IsccGridAlternateRowStyle" />
				<rowstyle cssclass="IsccGridRowStyle" />
				<selectedrowstyle backcolor="Yellow" />
				<columns>
					<asp:commandfield selecttext="Select" buttontype="Link" showselectbutton="true" />
					<asp:boundfield datafield="chargenumber" headertext="Charge Number" readonly="True" sortexpression="chargenumber">
						<headerstyle width="100px" />
					</asp:boundfield>
					<asp:boundfield datafield="divisionname" headertext="Division Name" readonly="True" sortexpression="divisionname">
						<headerstyle width="100px" />
					</asp:boundfield>
					<asp:boundfield datafield="fullname" headertext="Full Name" readonly="True" sortexpression="fullname">
						<headerstyle width="100px" />
					</asp:boundfield>
					<asp:boundfield datafield="id" headertext="ID" readonly="True" sortexpression="id">
						<headerstyle width="100px" />
					</asp:boundfield>
					<asp:boundfield datafield="organizationname" headertext="Organization Name" readonly="True" sortexpression="organizationname">
						<headerstyle width="100px" />
					</asp:boundfield>
					<asp:boundfield datafield="processreason" headertext="Process Reason" readonly="True" sortexpression="processreason">
						<headerstyle width="100px" />
					</asp:boundfield>
					<asp:boundfield datafield="worksite" headertext="Work Site" readonly="True" sortexpression="worksite">
						<headerstyle width="100px" />
					</asp:boundfield>
					<asp:boundfield datafield="yellowindexcolor" headertext="Yellow Index Color" readonly="True" sortexpression="yellowindexcolor">
						<headerstyle width="100px" />
					</asp:boundfield>
					<asp:boundfield datafield="zebraindexcolor" headertext="Zebra Index Color" readonly="True" sortexpression="zebraindexcolor">
						<headerstyle width="100px" />
					</asp:boundfield>
				</columns>
			</iscc:coolgridview>
		</p>
	</div>
	</form>
</body>
</html>

This is the code-behind...

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;

/// <summary>
/// This page shows a test to demonstrate that the selected-index persists after postback.
/// </summary>
public partial class CoolGridTestPage04 : System.Web.UI.Page
{
	#region MemberEnums

	public enum PersonRecordAttributeName
	{
		isactive
	}

	public enum CollectionName
	{
		personrecords
	}

	public enum TableName
	{
		personrecord
	}

	public enum PersonRecordColumnName
	{
		chargenumber,
		divisionname,
		fullname,
		id,
		organizationname,
		processreason,
		worksite,
		yellowindexcolor,
		zebraindexcolor
	}

	#endregion //MemberEnums

	#region HandlerMethods

	protected void Page_Load(object sender, EventArgs e)
    {
		try
		{
			if ((!this.IsPostBack) && ((this.MainGridView == null) || 
				(this.MainGridView.Rows == null) || 
				(this.MainGridView.Rows.Count <= 0)))
			{
				string myFilePath = Server.MapPath("~");
				const string myFileName = "TestData01.xml";
				string myFullPath = Path.Combine(myFilePath, myFileName);
				Debug.WriteLine("myFullPath='" + myFullPath + "'");
				XDocument xmlDoc = XDocument.Load(myFullPath);

				var q = from c in xmlDoc.Descendants(TableName.personrecord.ToString())
						where c.Attribute(PersonRecordAttributeName.isactive.ToString()).Value == bool.TrueString.ToLower()
						select new
						{
							chargenumber = c.Element(PersonRecordColumnName.chargenumber.ToString()).Value,
							divisionname = c.Element(PersonRecordColumnName.divisionname.ToString()).Value,
							fullname = c.Element(PersonRecordColumnName.fullname.ToString()).Value,
							id = c.Element(PersonRecordColumnName.id.ToString()).Value,
							organizationname = c.Element(PersonRecordColumnName.organizationname.ToString()).Value,
							processreason = c.Element(PersonRecordColumnName.processreason.ToString()).Value,
							worksite = c.Element(PersonRecordColumnName.worksite.ToString()).Value,
							yellowindexcolor = c.Element(PersonRecordColumnName.yellowindexcolor.ToString()).Value,
							zebraindexcolor = c.Element(PersonRecordColumnName.zebraindexcolor.ToString()).Value
						};

				this.MainGridView.DataSource = q;
				this.MainGridView.DataBind();
			}
		}
		catch (Exception ex)
		{
			this.MessageLabel.Text = ex.ToString();
		}
	}

	protected void MainGridView_Sorting(object sender, GridViewSortEventArgs e)
	{
		try
		{
			this.MessageLabel.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fffffff tt zzz") + ": " + "Sorting is not implemented.";
		}
		catch (Exception ex)
		{
			this.MessageLabel.Text = ex.ToString();
		}

	}

	#endregion //HandlerMethods
}

HTH.

Thank you.

-- Mark Kamoski

 

Mar 24, 2010 at 2:43 PM

Hi, thanks for your answer. I read your code, but I didn't found the focus setting. My current problem is the following:

1. Click on one row of the gridview.

2. After click open a content panel with rows data.

3. Click (submit) on the content panel return to parent page and refresh gridview data, but the selected row of the gridview lost focus.

I would like to set the focus on gridview after click on the content panel.

Thanks.

 

Mar 24, 2010 at 2:48 PM
vtamas wrote:

Hi, thanks for your answer. I read your code, but I didn't found the focus setting. My current problem is the following:... 2. After click open a content panel with rows data....

 

Vtam --

I have some follow-up questions for you regarding this.

Question 1:

You mention a control called a "content panel".

Exactly what do you mean by "content panel"?

What type of control is that? Do you mean an "asp:panel" control? Something else?

Question 2:

Also, regarding that control, where does it exist? Is it in the grid? Is it outside the grid? Where?

Question 3:

Are you changing the grid to "edit mode" so that you can do row-level edits inside the grid itself?

You mentioned a "selected row" in your seminal post so I thought you were just selecting the row but maybe you are "selecting the row and editing it in the grid"?

Please advise.

Thank you.

-- Mark Kamoski

 

Mar 24, 2010 at 3:03 PM

HI. My GridView is inside a panel and this panel’s functions are extending with CollapsiblePanelExtender. I must modify the gridview data. To data editing I use a new panel. In this panel is the “ContentPanel”.

Click row -> show content panel -> edit data on content panel -> Click “OK” on content panel ->return gridview.

The controls are on the content panel not in the gridview.

I don’t use gridview edit mode.

 I can send a little video from work.

 Thanks.

Mar 24, 2010 at 3:06 PM

I'd like to set focus on page PreRender methode.

 

            if (Session["S_NEWS_INDEX"] != null)
            {
                int myModifNewsRow = (int)Session["S_NEWS_INDEX"];
                this.grvNews.Rows[myModifNewsRow].BackColor = Color.Red;
                this.grvNews.Rows[myModifNewsRow].Focus();
            }

 

            if (Session["S_NEWS_INDEX"] != null)
            {
                int myModifNewsRow = (int)Session["S_NEWS_INDEX"];
                this.grvNews.Rows[myModifNewsRow].BackColor = Color.Red;
                this.grvNews.Rows[myModifNewsRow].Focus();

            }

The S_NEWS_INDEX is the selected row number.

 

 

Mar 24, 2010 at 3:12 PM

Vtam --

I see.

Given that scenario, I would set maintainscrollpositiononpostback="true" on the page.

If that did not work, then I would set the Currently-Selected-Index into Session on

GridView_SelectedIndexChanged event and then I would read-it out of Session on-demand as needed.

As a side note, one thing that is a bit curious to me is the fact that you say you are using

CollapsiblePanelExtender (which is Ajax right?) and yet you are hooking a PostBack (which is not Ajax right?).

That sounds odd to me and I am wondering if the event-cycle is not a bit too complex, making matters hard to program.

What do you think?

HTH.

Thank you.

-- Mark Kamoski

Mar 24, 2010 at 3:41 PM

Hi, maintainscrollpositiononpostback="true" is OK.

<%@ Page Language="C#" MasterPageFile="~/AuchanWS.Master" AutoEventWireup="true" CodeFile="ProcurementNew.aspx.cs"

    Inherits="ProcurementNew" Title="Untitled Page" EnableEventValidation="false" 
    EnableSessionState="True" EnableViewState="true" MaintainScrollPositionOnPostback="true"%>

I get the selected row number in the GridView_SelectedIndexChanged method and I write the session into S_NEWS_INDEX variable.

The CollapsiblePanelExtender is AJAX extender. You can see on : http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/CollapsiblePanel/CollapsiblePanel.aspx.

The PostBack is fired. The color change is work too

this.grvNews.Rows[myModifNewsRow].BackColor = Color.Red;

, just the focus is lost.

 

 

Thanks

 

Mar 24, 2010 at 3:48 PM
vtamas wrote:

...The PostBack is fired. The color change is work too...

Vtam --

Technically speaking, I think that is probably "the Ajax-based 'postback' is fired and the event handler runs".

However, I think that is probably not a "Page.PostBack", right?

 

Mar 24, 2010 at 4:00 PM

Yes, you are right, but I can catching this postback event on Page_Load and OnPreRender method too.

I checked on Page_Load and on OnPreRender to, but doesn't work.

 

Mar 24, 2010 at 4:08 PM
vtamas wrote:

....but I can catching this postback event on Page_Load and OnPreRender method too....

Vtam --

If that is accurate, then I would try...

...the page's pre-render event...

...the grid's pre-render event...

...the container control's pre-render event...

...but that is always a bit sticky and fuzzy....

...so, if it were me, I would probably do what I usually do in such cases--

...remove Ajax entirely, use the standard Page-based PostBack, get it working...

...and THAT will work and will be easy and quick to implement and will be clear, simple, and generic...

...then I would leave it as GEFN...

...but, and only if absolutely necessary per enduser requirements, I start to re-introduce Ajax incrementally and slowly and stop when it breaks.

The general rule of thumb that should be followed is...

Ajax is nice is a LUXURY and functionality must take precendence.

That is-- if one must choose between Ajax-niceties and things-actually-working, then one must always choose things-actually-working.

You may have one such case on your hands.

(I wish that I had better news-- but, that is the stark truth.)

HTH.

-- Mark Kamoski

Mar 25, 2010 at 9:11 AM

Hi, thanks for your all. I will create it without AJAX. Thanks Tamas

Mar 31, 2010 at 3:40 PM

Dear Mark. I have a problem again, please help me. I will use SmartNavigation property on the page. If the SmartNavigation="true", then the gridview has not scrollbar. Thanks.  

Mar 31, 2010 at 7:05 PM
Vtam -- FYI, I have opened a new Discussion on this SmartNavigation question. Please see the following link... http://ideasparks.codeplex.com/Thread/View.aspx?ThreadId=207954 I did so because it is a new Discussion, one that is different than the current Discussion. HTH. Thank you. -- Mark Kamoski
Apr 23, 2010 at 5:19 PM

Hy, i have the same problem, i need set focus on a desired row when gridwiew is shown

 grv.Rows[myIndexRow].Focus();  
the focus is kept only if the row is on first "page" when the scrollbar is at the top.
If i set focus on a row that is beyound the first scrollable area setting failed
and gridwiew always appears with scrollbar to the top position.
Some kind of solution?
Thank you very, very much.


 

Oct 18, 2013 at 11:44 AM