2009-06-09

Careful using rowIndex in an itemrenderer

The original title of this blog post was different to begin, but as I was coding I discovered that what I thought was going to be a great tip to share, was in fact not. You see I was trying to do some specialized display in an itemRendererer (in a DataGrid) but was not able to do it. As-is, each row in a particuliar column was displaying an amount, but the requirement came to me to display an amount range based on the value in the next row. For example, say the first row of data was displaying 2.00, and the amount value in the next row was 5.00...the first row should then display 2.00 - 4.99.

I was thinking I could accomplish this by using an itemRenderer and making use of the this.listData.rowIndex property to allow me to "know" the current index in the ArrayCollection, to therefore be able to get the data from the next row, if available. However the rowIndex property gives you the index of the current row being display by the itemRenderer, not the index in the ArrayCollection. Thus my idea backfired.

The reason is, the this.listData.rowIndex property returns the index of the current row being displayed, not the current index of the ArrayCollection as it is being traversed. So if your DataGrid (or any list control for that matter) is only displaying 4 rows, then the rowIndex property will only have values that go from 0 to 3; but your ArrayCollection might have X items in it, so its index will go from 0 to X - 1. And as the user scrolls the list control, although the rowIndex property will always have a range of 0 to 3, the current items from the ArrayCollection that are being displayed, might be items that have index of 14 to 17.

I still don't know how to resolve this issue, if anyone has any ideas, please let me know.

56 comments:

Joseph Labrecque said...

I was dealing with the same exact issue and actually shelved the project for a while.

I have no solution but would be super interested if anyone has one.

TimHoff said...

In your itemRenderer:

import mx.controls.DataGrid;

private var myOwner : DataGrid;

override public function set data(value:Object):void
{
super.data = value;

myOwner = owner as DataGrid;

var myOwnerDataProvider:ArrayCollection = myOwner.dataProvider as ArrayCollection;

var myIndex:int = myOwnerDataProvider.getItemIndex( data );

if ( index < myOwnerDataProvider.length - 1 )
{
var myNextObject : MyObject = myOwnerDataProvider.getItemAt( index + 1 );

// parse my amount range; using myNextObject amount
}

}

Not a pretty solution, but it works. This is typed code, so there may be some tweaking needed.

-TH

Dimitrios "Jimmy" Gianninas said...

The myOwnerDataProvider.getItemIndex( data ); is what I should have used...worked like a charm, thx Tim!

TimHoff said...

Oh wow, I didn't even realize that this was your blog Dimitios. Your posts have helped me a lot over the years. I'm glad that I could return the favor.

-TH

Dimitrios "Jimmy" Gianninas said...

What goes around, comes around Tim :)

TimHoff said...

True that. :)

Anonymous said...

jimmyflex.blogspot.com is very informative. The article is very professionally written. I enjoy reading jimmyflex.blogspot.com every day.
quick loans
payday advance

Anonymous said...

Use:

listData.rowIndex + DataGrid(owner).verticalScrollPosition

Anonymous said...

I want the iphone 3g but i dont have att..i was thinking about buying an unlocked one off of ebay
[url=http://forexrobot-review.info]best forex software[/url] [url=http://commondangers.net/dangers/viewtopic.php?p=14366#14366]unlock iphone[/url]

Anonymous said...

Hey I'd love to thank you for such a terrific quality forum!
thought this is a perfect way to introduce myself!

Sincerely,
Robin Toby
if you're ever bored check out my site!
[url=http://www.partyopedia.com/articles/farm-party-supplies.html]farm Party Supplies[/url].

Anonymous said...

[url=http://kfarbair.com][img]http://www.kfarbair.com/_images/logo.png[/img][/url]

מלון [url=http://www.kfarbair.com]כפר בעיר[/url] - [url=http://www.kfarbair.com/about.html]חדרים[/url] גדולים אנו מציעים שירותי אירוח מגוונים גם ישנו במקום שירות חדרים הכולל [url=http://www.kfarbair.com/eng/index.html]סעודות רומנטיות[/url] במחירים מיוחדים אשר מוגשות ישירות לחדרכם!

לפרטים נוספים נא לפנות לאתרנו - [url=http://kfarbair.com]כפר בעיר[/url] [url=http://www.kfarbair.com/contact.html][img]http://www.kfarbair.com/_images/apixel.gif[/img][/url]

vin said...

Hi

For a similar scenarion i used TimHoff solution of overridibg the set data method. I my case i will i will add rows to data grid in two ways. One way is assigning the
dataprovider which comes from a service call and the other is simply creating a new object and
adding to the collection.


Issue here is when the coll is empty and I add a new object to it
then the owner is DataGrid, but if
while assigning the coll from the service call the owner is some ListbaseContentHolder and owner.parent is DataGrir.

Does any one have clue abt this.

thanks
vin

Anonymous said...

Hello everyone
Do not miss your chance to get a free ipad. Visit http://bit.ly/cmmVr7

Scott Enders said...

Thank you for your post. I didn't even realize this was an issue until I happen to run across this blog post (while searching on something else). I went back to check my work and you were right.

I also ran into and issue of the scroll position getting screwy when I updated the dataProvider of the datagrid. I found that this link had a good solution:

How to data bind DataGrid component without scrolling up?

Anonymous said...

[url=http://www.kfarbair.com][img]http://www.kfarbair.com/_images/_photos/photo_big8.jpg[/img][/url]

מלון [url=http://www.kfarbair.com]כפר בעיר[/url] - אווירה כפרית, [url=http://www.kfarbair.com/about.html]חדרים[/url] מרווחים, שירות חדרים, אינטימיות, שלווה, [url=http://kfarbair.com/services.html]שקט[/url] . אנו מציעים שירותי אירוח מיוחדים גם ישנו במקום שירות חדרים המכיל [url=http://www.kfarbair.com/eng/index.html]ארוחות רומנטיות[/url] במחירים מפתיעים אשר יוגשו ישירות לחדרכם!

לפרטים נוספים אנא גשו לאתר האינטרנט שלנו - [url=http://kfarbair.com]כפר בעיר[/url] [url=http://www.kfarbair.com/contact.html][img]http://www.kfarbair.com/_images/apixel.gif[/img][/url]

Anonymous said...

Genial post and this mail helped me alot in my college assignement. Gratefulness you seeking your information.

Anonymous said...

Hey,

I mostly visits this website[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url]jimmyflex.blogspot.com is filled with quality info. Frankly speaking we really do not pay attention towards our health. Let me show you one truth. Recent Scientific Research presents that almost 70% of all U.S. grownups are either obese or overweight[url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips].[/url] Therefore if you're one of these individuals, you're not alone. Its true that we all can't be like Brad Pitt, Angelina Jolie, Megan Fox, and have sexy and perfect six pack abs. Now next question is how you can achive quick weight loss? You can easily lose with with little effort. You need to improve some of you daily habbits to achive weight loss in short span of time.

About me: I am writer of [url=http://www.weightrapidloss.com/lose-10-pounds-in-2-weeks-quick-weight-loss-tips]Quick weight loss tips[/url]. I am also health trainer who can help you lose weight quickly. If you do not want to go under painful training program than you may also try [url=http://www.weightrapidloss.com/acai-berry-for-quick-weight-loss]Acai Berry[/url] or [url=http://www.weightrapidloss.com/colon-cleanse-for-weight-loss]Colon Cleansing[/url] for effortless weight loss.

Anonymous said...

I'm fresh here n' I have needed to tell hello to you all :)

I have been visiting this web site for couple of dayz and it appeared as a dendy place to be a member of.

propecia said...

Hello friend amazing and very interesting blog about Careful using rowIndex in an itemrenderer I really enjoyed reading this blog and I would like to have any update about it, thanks for sharing!!

Anonymous said...

Thanks A LOT!!!
Such a great help, was sweating on this for several hours

Anonymous said...

shamwow
rotoshave review
quick lawn
Silver Sonic XL

Anonymous said...

security guard jobs
driving jobs

Jon said...

Just stumbled upon this entry via Google...

"myOwnerDataProvider.getItemIndex(data)"

BRILLIANT! Thank you all. I knew the ItemRenderer was recycling the rowIndex and this was a perfect solution.

Anonymous said...

bcllkml rvd damtd foot fetish

hytxa!

vvofj yxufyn pbn hentai anal

Anonymous said...

Hi

Recent winter has been for a few of us quite cold. Lack of heating cause that most people consider paying for [url=http://www.xn--agregat-prdotwrczy-31b96a.katowice.pl/wynajem-agregatow-pradotworczych/]wynajem agregatow pradotworczych[/url] to secure power when possible.


Best regards

Anonymous said...

epda xszbk Oral Sex ozgmbn r ax y tdg

Anonymous said...

ntdy wnbiz xnxx bpbqxm z vp n lpr

Anonymous said...

facebook likes
1000 facebook likes

http://entrepreneurship.unica-network.eu/content/peter-drucker-society-europe-launches-essay-contest http://bradpaisley.com/tour/nashville-tn-cma-fest-2011-06-09
buy facebook likes facebook likes buy facebook likes
I have AVG anti-virus, Spybot and Malware Bytes installed, can Microsoft Essentials replace all these? Does the Essentials program use alot of system resources?

1000 facebook likes buy facebook likes [url=http://1000fbfans.info]buy facebook likes [/url] get facebook likes

online viagra said...

hey buddy,this is one of the best posts that I�ve ever seen; you may include some more ideas in the same theme. I�m still waiting for some interesting thoughts from your side in your next post.

Anonymous said...

The most strange and amusing images and pictures online.
Counterfoil into public notice
[url=http://www.funnyimgz.blogspot.com]funny[/url]

Anonymous said...

これまでについて疑問ジパングカジノ? friend's son. Even in his eighteenth year Benjamin was consulted by Mr. Waterhouse, and begged him to put on the jacket which had been http://xn--79-mg4axag2fvhmi9cc.com オンラインカジノ攻略再訪 myself, but I just want to help you, Jim." オンラインカジノ 違法性上のチュートリアル [url=http://xn--79-mg4axag2fvhmi9cc.com ]オンラインカジノ 違法性 [/url][65] More probably Anche-diva, or Ange-diva.--Astl. I. 38. b. オンラインカジノ 比較

Anonymous said...

for yQEghQQK [URL=http://www.burberry-outlet2013.com/]burberry outlet online[/URL] for promotion code TOOGxDVl [URL=http://www.burberry-outlet2013.com/ ] http://www.burberry-outlet2013.com/ [/URL]

Anonymous said...

[url=http://kaufenviagragenerika50mg.net/]viagra kaufen[/url] viagra ohne rezept [url=http://achat-viagra-pascher.net/]viagra[/url] viagra [url=http://comprarviagragenerico100mg.net/]generico viagra[/url] viagra precio [url=http://comprareviagragenerico50mg.net/]costo viagra[/url] viagra vendita

Anonymous said...

[url=http://muhouransutechtwei.narod.ru/file120.html]игровые автоматы лошади бесплатно без регистрации[/url] виртуальное казино скачать , [url=http://muhouransutechtwei.narod.ru/file315.html]играть онлайн фараон игровые автоматы[/url] игровые автоматы в онлайне бесплатно , [url=http://muhouransutechtwei.narod.ru/file135.html]игровые автоматы гаминатор играть бесплатно[/url] азартные игры карты на раздевание , [url=http://muhouransutechtwei.narod.ru/file435.html]онлайн покер рубли юбилейные[/url] скачать игру азартный игрок , [url=http://muhouransutechtwei.narod.ru/file510.html]азартные игры автоматы играть бесплатно без регистрации алькатрас[/url] венецианский карнавал игровые автоматы

Anonymous said...

игровые автоматы онлайн бесплатно слоты онлайн [url=http://tinateadartiin.narod.ru/archive742.html]игровой автомат черт[/url] игровые автоматы колумб онлайн бесплатно , [url=http://tinateadartiin.narod.ru/archive700.html]слот автоматы играть[/url] онлайн покер на реальные деньги , [url=http://tinateadartiin.narod.ru/archive336.html]игровые автоматы 80-х бесплатно[/url] азартные игры бесплатно автоматы пчелка 2 , [url=http://tinateadartiin.narod.ru/archive84.html]онлайн покер старс[/url] адмирал онлайн казино , [url=http://tinateadartiin.narod.ru/archive350.html]слот автоматы онлайн бесплатно играть[/url]

Anonymous said...

пароль на онлайн покер шоу [url=http://tislitipatzsembneu.narod.ru/topic75.html]скачать программу игровые автоматы[/url] онлайн казино на деньги с начальным капиталом , [url=http://tislitipatzsembneu.narod.ru/topic50.html]азартные игры онлайн играть бесплатно без регистрации и смс[/url] игровые автоматы 15 линейные играть бесплатно шарики , [url=http://tislitipatzsembneu.narod.ru/topic375.html]азартные игры онлайн бесплатно играть сейчас[/url] игровые автоматы sharky , [url=http://tislitipatzsembneu.narod.ru/topic450.html]игровые автоматы resident играть бесплатно и без регистрации[/url] онлайн казино с md5 , [url=http://tislitipatzsembneu.narod.ru/topic275.html]виртуальное онлайн казино[/url]

Anonymous said...

интернет казино лас вегас [url=http://edpengotarmokhaz.narod.ru/casino456.html]азартные игры в тысячу[/url] игровые автоматы магия , [url=http://edpengotarmokhaz.narod.ru/casino708.html]азартные игры бесплатно играть сейчас поиск предметов[/url] украинские казино онлайн , [url=http://edpengotarmokhaz.narod.ru/casino432.html]интернет казино голдфишка отзывы[/url] игровые автоматы слоты бесплатные , [url=http://edpengotarmokhaz.narod.ru/casino600.html]игровые автоматы алькатрас играть бесплатно без регистрации мега джек[/url] игровые автоматы играть бесплатно игра гном

Anonymous said...

купить развлекательные игровые автоматы [url=http://troubevunbeadeppin.narod.ru/post437.html]играть игровые автоматы кони[/url] игры азартные клубничка онлайн бесплатно , [url=http://troubevunbeadeppin.narod.ru/post380.html]интернет казино игровые автоматы вулкан 750[/url] интернет казино сарапул , [url=http://troubevunbeadeppin.narod.ru/post76.html]азартные игры бесплатно без регистрации и смс[/url] слот автоматы бесплатно без регистрации , [url=http://troubevunbeadeppin.narod.ru/post190.html]игровые автоматы резидент без регистрации бесплатно[/url] игровые автоматы игры на компьютер , [url=http://troubevunbeadeppin.narod.ru/post551.html]онлайн покер в браузере opera[/url]

Anonymous said...

After looking into a number of the articles on your web site,
I truly appreciate your way of writing a blog. I book marked it to my bookmark webpage list
and will be checking back in the near future. Please visit my website too
and tell me how you feel.

My web-site :: weight loss

Anonymous said...

beats by dre tcmudgee casque beats by dre pas cher kdancxmx casque beats by dre kyfpukgy casque docteur dre jvthojav casque monster beats pas cher uczkdqys casque monster beats unoctxrw ecouteur beats grvmpryg monster beats pas cher xhnlkcev monster beats hvnguhtj

Anonymous said...

ghd nz vrvnvjrr ghd nz sale zbedfvfo ghd ophiumse

Anonymous said...

click [URL=http://louisvuittonbuy.blogcindario.com/2012/11/00002-louis-vuitton-buy-with-unique-style-and-top-quality-online.html]louis vuitton buy[/URL] online EEPmGpKy [URL=http://sagadoor.com/archives/5896 ] http://krishnacommunity.com/wheretobuylouisvuitton/ [/URL]

Anonymous said...

sell [URL=http://guccionlineoutletrr.exteen.com/]gucci online outlet[/URL] for less xqJHZmty [URL=http://worldmusicblog.net/guccionlineshopyy/ ] http://guccionlineee.marquette.blogs.propertysolutions.com/ [/URL]

Anonymous said...

http://www.cafb29b24.org/docs/buyativan/#medication 3 mg ativan withdrawal - lorazepam 1mg clonazepam

Anonymous said...

Have somebody that may be there for yourself as soon as the pain is significant. Having a helping hands, if they are doing gentle chores for you personally or assisting you cope with the house without having damage or unwanted stress on your bones, may be a great way to ensure you are usually equipped to manage joint inflammation with out placing too much on yourself. [url=http://www.x21w12w21.info]Vi7765ity[/url]

Trinityserviceshvac said...

This is typed code, so there may be some tweaking needed.
Air Conditioning Repair New Orleans

Anonymous said...

интернет казино платформа [url=http://agnersabankgalen.narod.ru/file252.html]казино онлайн эстонии[/url] интернет казино еврогранд отзывы 2012.

Anonymous said...

It's an awesome post for all the internet viewers; they will take benefit from it I am sure.

Feel free to visit my blog: the tao of badass

Anonymous said...

You're so interesting! I don't believe I've truly read through a single thing like this before. So wonderful to find someone with some unique thoughts on this subject. Seriously.. thank you for starting this up. This site is one thing that is needed on the internet, someone with a bit of originality!

Also visit my site; ルブタン

Anonymous said...

Whats up very cool blog!! Man .. Excellent .. Amazing .

. I'll bookmark your site and take the feeds additionally? I am happy to find so many helpful information here in the put up, we'd like
work out extra strategies on this regard, thank you
for sharing. . . . . .

Feel free to visit my site; クリスチャンルブタン

Anonymous said...

Hey there this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML.
I'm starting a blog soon but have no coding know-how so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!

My web-site :: http://www.marioiezziartista.it/

Anonymous said...

I really love your site.. Pleasant colors & theme.

Did you make this website yourself? Please reply back as I'm planning to create my very own website and would love to learn where you got this from or just what the theme is called. Cheers!

My web page: モンスタービーツ

Anonymous said...

Кабельная продукция - один из основных продуктов, применяемых для полнофункциональной деятельности электрооборудования. Разнообразие моделей и марок кабеля на сайте ООО "Спецкомплект" Предлагают широкий выбор для оптового и розничного покупателя.
Фирма предлагает ассортимент популярных товаров, таких как К1163, К1150, К1151, К1152, Арматура для СИП ENSTO, КВВГ, КВбБШв, АС,ДКС, оптический кабель ОКГ, ОКБ, ОКЛ, ОКК.
Сборка щитового оборудования высокого качества по доступной цене, смотрите обзор на сайте компании.
Specomplect.ru: [url=http://specomplect.ru]лотки ЛПМЗТ[/url]

Anonymous said...

Возведение жилых и индустриальных многоуровневых объектов влечет за собой привлечение специальной строительной техники, оснащенной для проведения определенных задач. Проведение строительных работ происходит по этапам, в связи, с чем, задействовать строительную технику тоже доводится по шагам, в зависимости от определенных задач.
Но покупка таковой особой техники влечет большие расходы. Так как стоит она дорого, компания "Сапрос" рекомендует услуги аренды строительной техники. Наш автопарк укомплектован всем важным для строительства автотранспортом. Моментальный заказ спецтехники можно создать через интернет, заполнив заявку онлайн на сайте фирмы. В Самаре мы пользуемя популярностью именно за высококачесвенное и быстрое обслуживание посетителей, предоставляя такую услугу, как аренда бары в самаре. Наши специалисты при необходимости в полном объеме проконсультируют Вас о более подходящем под запросы автотранспорте, что позволит сэкономить и время и деньги.
Sapros.Ru: [url=http://sapros.ru]аренда экскаватора погрузчика в самаре[/url]

shesa said...

replica zara bags replica bags hermes replica bags paypal

Unknown said...

k8p15l4y29 k0e23r5l99 i9l75f0z97 o2l47d3g01 i2s07n5c53 x3l82j8t90