Question

Using Legend Colors to Populate DataGrid Backgrounds

Asked by: hockeyragazzo

Hello everyone,

Right now I have data retrieved from PHP that populates an AdvancedDataGrid via an ArrayCollection. I also use the same data to fill up another array collection that is bound to a pie chart to display the data graphically. Now what I want to do here is, instead of having a legend, have a column in the datagrid called "Legend" that shows the relevant slice of the pie. From what I can tell, what I need is:

- A way to dynamically determine the hex color chosen by Flex for a particular ticker in the array.
- A way to color the background of a cell in a Datagrid depending on that row's ticker symbol.

If I know these things, I think I can probably figure it out from there.

Thanks

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-01-25 at 20:04:56ID24082574
Tags

Flex 3

,

actionscript 3

Topics

Adobe Flex

,

ActionScript

Participating Experts
1
Points
500
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Creating a 512 item Legend Window
    Hi Experts, I am currently trying to create a Legend Window for an application I'm writing. This legend will show how a graphics layer, appearing in a map window, featuring many coloured dots is coloured . In some instances one layer may have in excess of 500 unique values...
  2. how to set button legend on datagridview in vb.net 2005
    Hi, I have a datagrid view that is bound to a dataset. I have also added an extra button manually to the datagrid view but am having trouble on setting the legend of the button to "delete". How do I do this please. Many thanks Lee
  3. Is there a way to change the style of the datagrid for Flex 3
    Flex 3 datagrid is pretty awesome, but it's pretty limited in styling options. Is there a way to change the default styling of the datagrid. example, the cell margin, is there a way to change that? Thanks
  4. Flex Datagrid Cell Validation
    Hello, I am new to flex. Following is what I am trying to do. 1. Datagrid with 6 columns 2. Out of the 6 columns, 2 columns are combobox 3. I have 2 categories of validation for the values entered in the cell. a. Some simple validation like value entered cannot be null o...
  5. export flex 3 datagrid to excel
    What is the simpliest way to export the data inside a flex 3 datagrid to an Excel spreadsheet?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: zzynxPosted on 2009-01-26 at 04:57:05ID: 23466100

>> A way to dynamically determine the hex color chosen by Flex for a particular ticker in the array.
No doubt you'll find these interesting:
* Changing the default fill colors in a Flex PieChart control: http://blog.flexexamples.com/2007/11/11/changing-the-default-fill-colors-in-a-flex-piechart-control/
* Creating custom fills in a Flex PieChart control using the fillFunction property: http://blog.flexexamples.com/2007/11/07/creating-custom-fills-in-a-flex-piechart-control-using-the-fillfunction-property/

>> A way to color the background of a cell in a Datagrid depending on that row's ticker symbol
Changing row background color in AdvancedDataGrid: http://flexpearls.blogspot.com/2008/02/row-background-color-in.html

 

by: hockeyragazzoPosted on 2009-01-27 at 09:53:03ID: 23479116

Those sites helped a bit, but I'm still unsure of how to do this. To clarify, I'm trying to have one column in a datagrid entirely dedicated to being a "legend." Let's say Google (ticker GOOG) is in rows 7, 8, 9, and 10. I want cells 7, 8, 9, and 10 to have the same background color as the pie slice for GOOG.

Perhaps I could iterate through the pie chart and create an Object that has the Ticker and pie color information, then I could refer to that in the specific datagrid cells? Something like...if this row's ticker == GOOG, set this column's cell color = myObj.GOOG (which would be a hex color string).

 

by: zzynxPosted on 2009-01-28 at 00:26:30ID: 23484454

I understand what you mean.

I don't know a way to "grab" the colors used by the Flex PieChart, so that's why I gave you a link on how to set them yourself. That way you don't have to iterate through it, cause you chose them yourself. That's the solution for your first point.

The other link shows you how to set the background of a complete row.
This link (http://blog.flexexamples.com/2008/09/24/setting-background-colors-on-a-datagrid-column-in-flex/) tells you how to set the color of a complete column.
But you want to set the color of just one cell?
Well, this might be useful: http://butterfliesandbugs.wordpress.com/2007/07/11/using-an-itemrenderer-to-change-the-background-of-a-datagrid-cell/ (sample code available)

 

by: hockeyragazzoPosted on 2009-02-03 at 15:19:36ID: 23543493

Sorry for the delayed response (I was off in NYC for the weekend). I'm going to poke around the Flex docs to see if I can't come up with a way to retrieve the default pie slice information that Flex sets. I see what you're saying with setting my own colors (indeed, I had stumbled across that site before I asked the question here), but imagine the search pulls back 200 securities and I've only set 150. Then there may not be a unique color for each security, which may or may not be a problem. I find it hard to believe that the Flex devs would create a default color set and not allow you to read which color is currently being used by which spot in an array. I'll let you know what I find on this front.

The custom item renderer is going to be a tough nut to crack. I'll see what i can do there as well.

Thanks for your help so far.

 

by: zzynxPosted on 2009-02-04 at 00:03:42ID: 23545770

>> imagine the search pulls back 200 securities and I've only set 150
Two remarks:
1) If you use a pie chart with 200 different parts I think you should wonder if that's a good way to represent your data
2) I doubt if even Flex will use/find 200 (really) different colors

>> I find it hard to believe that the Flex devs would create a default color set and not allow you to read which color is currently being used by which spot in an array.
I tend to agree.

>> I'll let you know what I find on this front.
Good. I'm curious.

 

by: zzynxPosted on 2009-02-04 at 01:30:42ID: 23546170

>> A way to dynamically determine the hex color chosen by Flex for a particular ticker in the array.
Bingo!
I found it, as the code beneath illustrates

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
	creationComplete="onCreationComplete()"
	>
  <mx:Script><![CDATA[
  	import mx.graphics.SolidColor;
  	import mx.controls.Alert;
  	import mx.charts.LegendItem;
     import mx.collections.ArrayCollection;
     
     private var _myColor:SolidColor;
     
     [Bindable]
     public var expenses:ArrayCollection = new ArrayCollection([
        {Expense:"Taxes", Amount:2000},
        {Expense:"Rent", Amount:1000},
        {Expense:"Bills", Amount:100}
     ]);
     
     private function onCreationComplete():void {
		for (var i:int = 0; i<3; i++) {
		
			var legendItem:LegendItem = myLegend.getChildAt(i) as LegendItem;
			var color:SolidColor = legendItem.getStyle("fill") as SolidColor;
			switch (i) {
				case 0: lbl1.setStyle("color", color.color); break;
				case 1: lbl2.setStyle("color", color.color); break;
				case 2: lbl3.setStyle("color", color.color); break;
				default: break; 
			}
		}
     }
     
  ]]></mx:Script>
  
  <mx:Panel title="Pie Chart">
     <mx:PieChart id="myChart" 
        dataProvider="{expenses}" 
        showDataTips="true">
        <mx:series>
           <mx:PieSeries 
                field="Amount" 
                nameField="Expense" 
                labelPosition="callout"
           />
        </mx:series>
     </mx:PieChart>
     <mx:Legend id="myLegend" dataProvider="{myChart}"/>
     <mx:Label id="lbl1" text="Color of the first legenditem" />
     <mx:Label id="lbl2" text="Color of the second legenditem" />
     <mx:Label id="lbl3" text="Color of the third legenditem" />
  </mx:Panel>
</mx:Application>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:

Select allOpen in new window

 

by: hockeyragazzoPosted on 2009-02-04 at 08:13:59ID: 23549693

You are amazing...I'll see if I can't implement this tonight.

I agree that it will be a strange day when I have to fit 200 slices into a pie. For greater context, this pie will only be displaying the relative size of securities in an account's portfolio. Upon selection of an item in my Advanceddatagrid, the pie will explode to show the selected tranche.

I don't have access to a computer with Flex on it at the moment, so this post will have to be mostly theoretical in nature. I'm unsure of how itemrenderers are implemented, as I've only made a few forays into this area in the past, but as I understand it, the itemrenderer is called on creationComplete (of the ADG) and also when the dataprovider is changed. Since the itemrenderer's script is kept in a separate .as file, in what way, do you think, would it be most beneficial to retrieve the data from the Legend so as to fill in the cells of the ADG? Currently my limited scope only allows me to see a few options:

1. Upon receipt of the data from the server, after it has been entered into the PieChart (and through that, the legend), but before it has been entered into the dataprovider for the ADG, create an object (i.e. an associative array) with the ticker/color data from the Legend. Then go on to fill the ADG dataprovider and somehow (though I'm not sure how) retrieve this object in the .as file for the itemrenderer so I can say...this row's ticker is YYY, so set this cell's color value to myLegColorObj.[YYY].

2. Create the object inside the itemrenderer by accessing the Legend in the .as file, then proceed to use the object in the same way as #1.

My concern with this approach stems from my lack of understanding of how much freedom I have with an itemrenderer to step in and out of .mxml modules or applications. How easy is it, really, to refer to an object in, say, PieChartAndDataGrid.mxml from DataGridRenderer.as? If I were to import the PieChartAndDataGrid module into the .as file, will I be penalized in terms of having to load that .mxml? I only ask this because every time I try to migrate functions away from my individual modules by importing modules into the parentApplication (inside the <script> tags), it effectively loads the module when I run the parentApplication, and not when I call it separately. So to clarify my ramblings, will doing this in the .as file make any noticeable difference in the file sizes of the parentApplication vs. the PieChartAndDataGrid module:

import com.PieChartAndDataGrid;

Please let me know if any of this didn't make any sense. Thanks again for your help.

 

by: zzynxPosted on 2009-02-04 at 08:49:04ID: 23550146

I think your ADG should visualize objects X that have a "legendColor" attribute/field available (and of course all the others you need)

1) Get your data from the server
2) Feed it to the PieChart (+ hidden/invisible legend)
3) create and fill your array of X objects (the legendColor attribute you get from the Legend as I did, the others you get from 1)
4) Feed that to your ADG
5) As the link (http://butterfliesandbugs.wordpress.com/2007/07/11/using-an-itemrenderer-to-change-the-background-of-a-datagrid-cell/) I gave you shows: you have by default your X object (and hence its legendColor attribute) available inside the itemrenderer's updateDisplayList() method. And that's simply all you need to draw the right background color! No need for any other object that's inside PieChartAndDataGrid.

 

by: hockeyragazzoPosted on 2009-02-04 at 13:26:13ID: 23553717

I'm eager to get home to give this a try. You've been enormously helpful so far, zzynx, and I thank you for it!

 

by: hockeyragazzoPosted on 2009-04-11 at 22:46:37ID: 24124660

Ok I finally got the time to get this to work. Ultimately I did more or less as was described above. I stored the legend color data in an array in which I named the array spots after their Cusips (or Tickers) so that:

LegendColorData["AMZN"] has an identity that is a solidcolor that can be used when using setStyle("backgroundColor", LegendColorData[data.Ticker])

then I use a VBox itemrenderer with padding around the edges and a Canvas inside this padded area with rounded corners. I set the style of the row in my Legend column on an updateComplete event in the VBox so that each time the datagrid is updated, it runs a certain function backgroundColor() which sets the canvas's backgroundColor = data.Ticker (or in my case, data.Cusip, which is just another kind of security identifier). I've attached the relevant code and an image of the final result.

If you have any questions, ask here.

<mx:Script>
	<![CDATA[
 
        	public var LegendColorData:Array = new Array();
		[Bindable] public var pieChartA:Array;
		[Bindable] public var pieChartAC:ArrayCollection;
		public var pieDataTimer:Timer = new Timer(300, 1);
 
        	private function retrieveText(event:ResultEvent):void {
 
				if (String(event.result).length > 10000) {
					returnText.text = String(event.result).substring(0, 10000);
				} else {
					returnText.text = String(event.result);
				}
				jsonPosData = JSON.decode(String(event.result));
				var totalHoldingsRows:Number = Number(jsonPosData[0].totalRows);
				
				pieChartA = new Array();
 
				for (var i:Number=1; i<=totalHoldingsRows; i++) {
					var myPieObj:Object = new Object();
					myPieObj.Name = jsonPosData[i].SecurityDescrip;
					myPieObj.Ticker = jsonPosData[i].Ticker;
					myPieObj.Cusip = jsonPosData[i].Cusip;
					myPieObj.MarketValue = Number(jsonPosData[i].MarketValue);
					
					pieChartA.push(myPieObj);
				}
				
				
				pieChartAC = null;
				pieChartAC = new ArrayCollection(pieChartA);
				
				pieDataTimer.addEventListener(TimerEvent.TIMER_COMPLETE, getColorData);
				pieDataTimer.start();
				
        	}
 
        	public function getColorData(evt:TimerEvent = null):void {
				
				LegendColorData = new Array();
				
				for (var j:int=0; j<pielegend.numChildren; j++) {
					var thisItem:LegendItem = pielegend.getChildAt(j) as LegendItem;
					var thisColor:SolidColor = thisItem.getStyle("fill") as SolidColor;
					var thisCusip:String = pieChartA[j].Cusip;
					
					LegendColorData[thisCusip] = thisColor.color;
				}
				
				posDataGrid.invalidateList();
				
        	}
 
	]]>
</mx:Script>
 
		<mx:AdvancedDataGrid id="posDataGrid" designViewDataType="flat" width="100%" height="320" paddingBottom="0"
			defaultLeafIcon="{null}" folderClosedIcon="{null}" folderOpenIcon="{null}" itemDoubleClick="selectGrid(event, posDataGrid)"
			doubleClickEnabled="true" allowMultipleSelection="true" selectionMode="multipleRows" paddingTop="1">
			<mx:dataProvider>
				<mx:HierarchicalData id="gridProvider" source="{holdingsArrayCollection}" childrenField="TaxLots"/>
			</mx:dataProvider>
			<mx:columns>
				<mx:AdvancedDataGridColumn headerText="Acct" dataField="MWNumber" width="60"/>
				<mx:AdvancedDataGridColumn headerText="Legend" id="legendcol" width="70" visible="false" itemRenderer="components.LegendRenderer"/>
				<mx:AdvancedDataGridColumn headerText="Security Name" dataField="SecurityDescrip" width="200"/>
				<mx:AdvancedDataGridColumn headerText="Cusip" dataField="Cusip" width="80"/>
				<mx:AdvancedDataGridColumn headerText="Shares" dataField="Shares" id="sharescolumn" width="80" formatter="{Application.application.numberFormatter}"/>
				<mx:AdvancedDataGridColumn headerText="%" dataField="PercentPort" width="40"/>
				<mx:AdvancedDataGridColumn headerText="Price" dataField="Price" width="70"/>
				<mx:AdvancedDataGridColumn headerText="Market Value" dataField="MarketValue" width="150"/>
				<mx:AdvancedDataGridColumn headerText="Cost Basis" dataField="CostBasis" width="150"/>
				<mx:AdvancedDataGridColumn headerText="Unr. G/L" dataField="UnrealizedGL" width="150"/>
			</mx:columns>
		</mx:AdvancedDataGrid>
 
 
<!-------------Following is LegendRenderer.mxml---------------->
 
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" paddingBottom="2" paddingLeft="2" paddingRight="2" paddingTop="2" 
	updateComplete="backgroundColor()">
	
	<mx:Script>
		<![CDATA[
			import mx.core.Application;
			import modules.MainPositionsModule;
			
			public var posModule:MainPositionsModule = MainPositionsModule(Application.application.posloader.child);
 
			public function backgroundColor():void {
 
				colorcanvas.setStyle("backgroundColor", posModule.LegendColorData[data.Cusip]);
			}
			
		]]>
	</mx:Script>
	
	
	<mx:Canvas width="100%" height="100%" id="colorcanvas" cornerRadius="6" borderStyle="solid" borderThickness="0">
	</mx:Canvas>
</mx:VBox>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:

Select allOpen in new window

 

by: zzynxPosted on 2009-04-14 at 00:09:47ID: 24135527

Glad to hear you managed to work it out successfully.
Thanx 4 axxepting

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...