Editable Datagrid Column
I have to make a datagrid column editable during runtime based on the data. If the column has a specific data then the column should not be editable otherwise it should be editable. Can we do it in flex ? please show some pointers.
I don't have any examples , but you should probably have a custom itemrenderer for your datagrid which contains a textarea. In the itemrenderer should override set data( value:Object ):void. In that function you check a condition to see if the textarea "editable" value should be set to true or false. Below I have some pseudo-code.
<s:Itemrenderer>
override public function set data( value:Object ):void
if( object.decidingValue > 0 )
TnA.editable = false;
else
TnA.editable = true;
<s:TextArea id="TnA" />
</s:Itemrenderer>
or you could just put the code in the TextArea declaration
<s:TextArea id="TnA" editable="{data.decidingValue > 0}" />
(TextInput area is probably more appropriate than a textarea , but the logic is the same )
If this response was helpful please mark it as such.
Similar Messages
-
Cancel edition in a Datagrid Column
What i´m wishing to do is very simple, i just want to cancel an edition in a DataGrid column,
Loosing focus of the textbox confirms the edition, i wanted to place 2 buttons above the edition text box, cancel and confirm, but it seems to be impossible...
any idea?
thanks in advance!!Yea that seems to work fine for me so in full, with editing features
Custom Comp
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="182" height="72" >
<mx:Script>
<![CDATA[
private function handleOk():void {
this.data.someText = textInput.text
override public function set data(value:Object):void {
super.data = value;
textInput.text = data.someText
private function cancel():void {
textInput.text = data.someText;
]]>
</mx:Script>
<mx:TextInput id="textInput" x="10" y="10" />
<mx:Button x="10" y="40" label="Update" click="handleOk()"/>
<mx:Button x="85" y="40" label="Cancel" click="cancel()"/>
</mx:Canvas>
Application
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
private var ac:ArrayCollection = new ArrayCollection([
{someText : 'Line 1'},
{someText : 'Line 2'},
{someText : 'Line 3'},
{someText : 'Line 4'},
{someText : 'Line 5'},
{someText : 'Line 6'},
{someText : 'Line 7'},
{someText : 'Line 8'},
{someText : 'Line 9'},
{someText : 'Line 10'}
]]>
</mx:Script>
<mx:DataGrid x="71" y="90" dataProvider="{ac}">
<mx:columns>
<mx:DataGridColumn headerText="Column 1" dataField="someText" itemRenderer="Comp1" width="182"/>
<mx:DataGridColumn headerText="Column 2" dataField="col2"/>
<mx:DataGridColumn headerText="Column 3" dataField="col3"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
Hope this helps
Andrew -
Setting the editable property of a datagrid column dynamically
Hi,
Im trying to set the editable property and renderer is editable property for a datagrid column to false on the creation complete event of the datagrid.But It does not work.While visible property works.why doesnt the editable property work.The particular column has a renderer which is a text box.and the editable property is set to false initially.Any Suggestions or ideas on how to achieve this will be of great help.Eu tenho vontade de estar devidamente por dentro de tudo isso.
-
How can I get this example to wok with <mx:HTTPService>
insead of the inline <mx:XML> ?
Dynamic DataGrid columns
Example of how to dynamically create DataGridColumns
A completely dynamic DataGrid example.
This example uses the xml from the Flexstore example. It
examines the first product node and uses that to create the
definitions for the columns. There is some example logic to change
the columns properties.
It then instantiates the GataGrid and its columns array,
assigns the properties, and then the dataProvider, and then adds
the dataGrid to the application container.
The example is fully self-contained, since a portion of the
catalog.xml file is included in the mxml.
<?xml version="1.0" encoding="utf-8"?>
<!-- This example uses the dataProvider to build the
dataGrid columns dynamically -->
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml"
layout="vertical"
creationComplete="initApp()">
<mx:Script><![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
import mx.controls.DataGrid;
import mx.collections.XMLListCollection;
import mx.controls.Alert;
[Bindable]
private var _xlcCatalog:XMLListCollection; //the
dataProvider for the DG
//run by creationComplete
public function initApp():void
_xlcCatalog = new XMLListCollection(xmlCatalog.product);
//wrap the XML product nodes in an XMLListCollection
buildDG(); //creates the dataGrid
}//initApp
private function buildDG():void
var aColumnDef:Array = getColumnDefArray(); //returns a
noraml array of objects that specify DtaGridColumn properties
var oColumnDef:Object;
var dg:DataGrid = new DataGrid; //instantiate a new DataGrid
var dgc:DataGridColumn;
var aColumnsNew:Array = dg.columns
var iTotalDGWidth:int = 0;
for (var i:int=0;i<aColumnDef.length;i++) { //loop over
the column definition array
oColumnDef = aColumnDef
dgc = new DataGridColumn(); //instantiate a new
DataGridColumn
dgc.dataField = oColumnDef.dataField; //start setting the
properties from the column def array
dgc.width = oColumnDef.width;
iTotalDGWidth += dgc.width; //add up the column widths
dgc.editable = oColumnDef.editable;
dgc.sortable = oColumnDef.sortable
dgc.visible = oColumnDef.visible;
dgc.wordWrap = oColumnDef.wordWrap;
aColumnsNew.push(dgc) //push the new dataGridColumn onto the
array
dg.columns = aColumnsNew; //assign the array back to the
dtaGrid
dg.editable = true;
dg.width = iTotalDGWidth;
dg.dataProvider = _xlcCatalog; //set the dataProvider
this.addChild(dg); //add the dataGrid to the application
}//buildDG
//uses the first product node to define the columns
private function getColumnDefArray():Array
//Alert.show("colcount:" + xmlCatalog.toXMLString());
var aColumns:Array = new Array();
var node0:XML = xmlCatalog.product[0]; //get the first
"product" node
var xlColumns:XMLList = node0.children(); //get its child
nodes (columns) as an XMLList
var xmlColumn:XML
var oColumnDef:Object;
for (var i:int=0;i<xlColumns.length();i++) { //loop over
the xmlList
xmlColumn = xlColumns;
oColumnDef = new Object();
oColumnDef.dataField = xmlColumn.localName(); //make the
dataField be the node name
switch (oColumnDef.dataField) { //conditional column
property logic
case "name":
oColumnDef.width = 80;
oColumnDef.sortable = false;
oColumnDef.visible = true;
oColumnDef.editable = false;
oColumnDef.wordWrap = false;
break;
case "description":
oColumnDef.width = 200;
oColumnDef.sortable = false;
oColumnDef.visible = true;
oColumnDef.editable = false;
oColumnDef.wordWrap = true;
break;
case "price":
oColumnDef.width = 40;
oColumnDef.sortable = true;
oColumnDef.visible = true;
oColumnDef.editable = true;
oColumnDef.wordWrap = false;
break;
case "image":
oColumnDef.width = 100;
oColumnDef.sortable = false;
oColumnDef.visible = false;
oColumnDef.editable = false;
oColumnDef.wordWrap = false;
break;
default:
oColumnDef.width = 50;
oColumnDef.sortable = true;
oColumnDef.visible = true;
oColumnDef.editable = false;
oColumnDef.wordWrap = false;
break;
aColumns.push(oColumnDef);
return aColumns; //return the array
}//getColumnDefArray
]]></mx:Script>
<mx:XML id="xmlCatalog">
<catalog>
<product productId="1">
<name>Nokia 6010</name>
<description>Easy to use without sacrificing style,
the Nokia 6010 phone offers functional voice communication
supported by text messaging, multimedia messaging, mobile internet,
games and more</description>
<price>99.99</price>
<image>assets/pic/Nokia_6010.gif</image>
<series>6000</series>
<triband>false</triband>
<camera>false</camera>
<video>false</video>
<highlight1>MMS</highlight1>
<highlight2>Large color display</highlight2>
</product>
<product productId="2">
<name>Nokia 3100 Blue</name>
<description>Light up the night with a
glow-in-the-dark cover - when it's charged with light you can
easily find your phone in the dark. When you get a call, the Nokia
3100 phone flashes in tune with your ringing tone. And when you
snap on a Nokia Xpress-on™ gaming cover*, you'll get
luminescent light effects in time to the gaming
action.</description>
<price>139</price>
<image>assets/pic/Nokia_3100_blue.gif</image>
<series>3000</series>
<triband>true</triband>
<camera>false</camera>
<video>false</video>
<highlight1>Glow-in-the-dark</highlight1>
<highlight2>Flashing lights</highlight2>
</product>
<product productId="3">
<name>Nokia 3100 Pink</name>
<description>Light up the night with a
glow-in-the-dark cover - when it's charged with light you can
easily find your phone in the dark. When you get a call, the Nokia
3100 phone flashes in tune with your ringing tone. And when you
snap on a Nokia Xpress-on™ gaming cover*, you'll get
luminescent light effects in time to the gaming
action.</description>
<price>139</price>
<image>assets/pic/Nokia_3100_pink.gif</image>
<series>3000</series>
<triband>true</triband>
<camera>false</camera>
<video>false</video>
<highlight1>Glow-in-the-dark</highlight1>
<highlight2>Flashing lights</highlight2>
</product>
<product productId="4">
<name>Nokia 3120</name>
<description>Designed for both business and pleasure,
the elegant Nokia 3120 phone offers a pleasing mix of features.
Enclosed within its chic, compact body, you will discover the
benefits of tri-band compatibility, a color screen, MMS, XHTML
browsing, cheerful screensavers, and much more.</description>
<price>159.99</price>
<image>assets/pic/Nokia_3120.gif</image>
<series>3000</series>
<triband>true</triband>
<camera>false</camera>
<video>false</video>
<highlight1>Multimedia messaging</highlight1>
<highlight2>Animated screensavers</highlight2>
</product>
<product productId="5">
<name>Nokia 3220</name>
<description>The Nokia 3220 phone is a fresh new cut
on some familiar ideas - animate your MMS messages with cute
characters, see the music with lights that flash in time with your
ringing tone, download wallpapers and screensavers with matching
color schemes for the interface.</description>
<price>159.99</price>
<image>assets/pic/Nokia_3220.gif</image>
<series>3000</series>
<triband>false</triband>
<camera>true</camera>
<video>false</video>
<highlight1>MIDI tones</highlight1>
<highlight2>Cut-out covers</highlight2>
</product>
</catalog>
</mx:XML>
</mx:Application>It should work the same way.
What problem are you having?
Tracy -
Editable DataGrid With DateField
I'm new to flex and struggling with the editable DataGrid. I
have a DataGrid with an ItemRenderer that outputs a DateField. I
can't figure out how to get the new value of the DateField after
the edit.
Here is my DataGrid (the endDate column):
<mx:DataGrid id="allHistoryGrid"
dataProvider="{allEntries}" height="313" width="782" y="-4"
itemEditEnd="saveGridChange(event)" editable="true">
<mx:columns>
<mx:Array>
<mx:DataGridColumn dataField="dietDescription"
headerText="Diet"/>
<mx:DataGridColumn dataField="allergyDescription"
headerText="Allergy"/>
<mx:DataGridColumn dataField="labDescription"
headerText="Lab"/>
<mx:DataGridColumn dataField="labResult" width="50"
headerText="Result" itemRenderer="LabResultItemRenderer"/>
<mx:DataGridColumn dataField="medicationDescription"
headerText="Medication"/>
<mx:DataGridColumn dataField="height" width="65"
headerText="Height" itemRenderer="HeightItemRenderer"/>
<mx:DataGridColumn dataField="weight" headerText="Weight"
itemRenderer="WeightItemRenderer"/>
<mx:DataGridColumn dataField="bmi" width="35"
headerText="BMI" itemRenderer="BmiItemRenderer"/>
<mx:DataGridColumn dataField="circumference" width="45"
headerText="Circ." itemRenderer="CircumferenceItemRenderer"/>
<mx:DataGridColumn headerText="Start Date" width="75"
sortCompareFunction="startDateSortCompare">
<mx:itemRenderer>
<mx:Component>
<mx:VBox clipContent="false">
<mx:DateFormatter id="dateFormatter"
formatString="MM/DD/YYYY"/>
<mx:Text width="100"
text="{dateFormatter.format(data.startDate)}"/>
</mx:VBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
<mx:DataGridColumn dataField="endDate" width="45"
headerText="End Date" itemRenderer="EndDateItemRenderer"
rendererIsEditor="true"/>
<mx:DataGridColumn id="deleteEntry" width="50"
textAlign="center"
headerText="Delete" sortable="false"
itemRenderer="DeleteItemRenderer"/>
</mx:Array>
</mx:columns>
</mx:DataGrid>
Here is my itemRenderer:
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="
http://www.adobe.com/2006/mxml"
paddingLeft="16" horizontalAlign="center">
<mx:DateFormatter id="dateFormatter"
formatString="MM/DD/YYYY"/>
<mx:DateField x="16" y="67" id="AllHistoryEndDate"
text="{dateFormatter.format(data.endDate)}"/>
</mx:VBox>
How do I get the new value in the saveGridChange function?
private function saveGridChange(event:DataGridEvent):void {That gives me this error:
TypeError: Error #1034: Type Coercion failed: cannot convert
EndDateItemRenderer@51a70a1 to mx.controls.TextInput. -
Datagrid column header word wrap issue
Hi All,
I'm passing dynamic text to a datagrid column header. The word wrap is true but it's not working.
Any ideas how to fix this issue?
DataGridColumn headerText="{myVar.text} Total" headerWordWrap="true"
Thanks
Johnny@Johnny,
Try to make use of the headerRenderer property and use <mx:Text /> control as a renderer so that your headerText gets wrapped..
Thanks,
Bhasker
Message was edited by: BhaskerChari -
Adding a Tree into a datagrid column
I have a requirement where I have to create a datagrid with
one of the columns having a tree control. The problem I am trying
to resolve is how to dynamically change the height of the datagrid
column which has the tree when the tree is collapsed and
dynamically increase the datagrid column height when the tree is
expanded.
Is is feasible ? Am I chasing a wild dream ?
Any help will be greatly appreciated...
ThanksDarin,
Thank you for responding. I was able to get a tree display in
a datagrid. I am going to attach all the code.
The problem I am facing is, I need two clicks to expand a
tree in the datagrid column so that both the tree to expand and the
datagrid column to adjust its height. Let me know why this is so.
May be, being a newbie, I am completely off the track here. Thanks
in advance.
THE MXML
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml"
layout="absolute" xmlns:ns1="com.ram.flash.custom.*">
<mx:XML id="xmlData" source="myDataWithTree.xml"/>
<mx:HBox>
<mx:DataGrid id="dgSource"
dataProvider="{xmlData.person}" editable="false"
variableRowHeight="true">
<mx:columns>
<mx:Array>
<mx:DataGridColumn editable="false" sortable="false"
resizable="true" width="400" textAlign="left" headerText="Id"
dataField="address">
<mx:itemRenderer>
<mx:Component>
<ns1:PruDataGridTreeColumn
disclosureOpenIcon="@Embed(source='icn_minus.jpg')"
disclosureClosedIcon="@Embed(source='icn_plus.jpg')" width="260"
height="20" />
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
<mx:DataGridColumn headerText="Name" dataField="name"
editable="false"/>
<mx:DataGridColumn headerText="Age" dataField="age"
editable="false"/>
</mx:Array>
</mx:columns>
</mx:DataGrid>
</mx:HBox>
</mx:Application>
THE DATA
<?xml version="1.0" encoding="UTF-8" ?>
<data>
<person>
<name>Mister</name>
<age>36</age>
<address>
<Capitals label="U.S. State Capitals">
<capital label="AL" value="Montgomery"/>
<capital label="AK" value="Juneau"/>
<capital label="AR" value="Little Rock"/>
<capital label="AZ" value="Phoenix"/>
<capital label="AL" value="Montgomery"/>
<capital label="AK" value="Juneau"/>
<capital label="AR" value="Little Rock"/>
<capital label="AZ" value="Phoenix"/>
<capital label="AL" value="Montgomery"/>
<capital label="AK" value="Juneau"/>
<capital label="AR" value="Little Rock"/>
<capital label="AZ" value="Phoenix"/>
</Capitals>
</address>
</person><person>
<name>Missus</name>
<age>28</age>
<address>
<Capitals label="Indian State Capitals">
<capital label="AL" value="Montgomery"/>
<capital label="AK" value="Juneau"/>
<capital label="AR" value="Little Rock"/>
<capital label="AZ" value="Phoenix"/>
</Capitals>
</address>
</person>
</data>
THE CUSTOM ACTIONSCRIPT CLASS
package com.ram.flash.custom
import flash.geom.Rectangle;
import mx.core.IDataRenderer;
import mx.controls.listClasses.IListItemRenderer;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import mx.managers.ISystemManager;
import mx.controls.Tree;
import flash.display.Sprite;
import flash.display.DisplayObject;
import mx.events.FlexEvent;
import mx.collections.XMLListCollection;
import flash.events.MouseEvent;
import mx.controls.treeClasses.TreeItemRenderer;
import mx.controls.treeClasses.TreeListData;
import mx.core.ClassFactory;
import mx.events.ScrollEvent;
import mx.controls.DataGrid;
import mx.events.CollectionEvent;
import mx.events.CollectionEventKind;
public class PruDataGridTreeColumn extends Tree implements
IListItemRenderer, IDataRenderer
private var _data : Object = null;
private var _dataGrid:DataGrid = null;
[Bindable("dataChange")]
public override function get data():Object
return _data;
public function set myDataGrid(value:DataGrid):void
_dataGrid = value;
public function PruDataGridTreeColumn()
super();
public override function set data(value:Object):void
this._data = value;
this.invalidateProperties();
var xmlDATA:XMLList = new XMLList(_data);
this.labelField='@label';
this.dataProvider = xmlDATA.address.Capitals;
dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
override public function expandItem(item:Object,
open:Boolean, animate:Boolean=false, dispatchEvent:Boolean=false,
cause:Event=null):void
animate = true;
super.expandItem(item,open,animate,dispatchEvent,cause);
var lc:XML = new XML(item);
var ht:Number = 20;
var wt:Number = this.width;
if(open)
ht = (lc.children().length() * 20 + 40);
this.height = (lc.children().length() * 20 + 40);
else
ht = 20;
this.height = 20;
} -
short version:
Is there a clever way to "un-sort" a datagrid column so the
Column and Grid will go back to the original pre-sorted state?--not
just remove the ability to sort.
long-winded background:
I'm using a ComboBox to toggle between report views (which
are displayed in a DataGrid). I have 2 views: the All View and the
Grouped View. The trouble I'm having is that once a column in my
DataGrid gets sorted by a User (which is desirable) in the All
View, then when the User toggles to the Grouped View the sort is
still in place for the column (not desirable). Upon toggle (via
ComboBox change event), I first clear out the DataProvider of all
data, then I'm setting the "sortable" property of the individual
columns and the DataGrid to be 'false' and then I'm repopulating
the DataProvider with fresh data. The result is that the ability to
sort the datagrid is indeed taken away from the User, but the new
data still appears sorted by the column.
dataAC.removeAll(); // ArrayCollection DataProvider to my
DataGrid
// Grouped View
for (var j:int=0;j<graphDG.columns.length;j++) {
var dgc: DataGridColumn = graphDG.columns[j] as
DataGridColumn;
dgc.sortable = false;
graphDG.sortableColumns = false;
...// refill dataACHello feldt12,
This will clear the sort:
ListCollectionView(dataGrid.dataProvider).sort = null;
ListCollectionView(dataGrid.dataProvider).refresh();
Thanks,
Philip
Message was edited by: Philip Keiter -
Setting datagrid column width according to itemrenderer.
Hi all,
This is my first question ever in any forum i have visited, so if you find anything stupid about my way of asking question then Pls ignore.
I have taken a datagrid and for one of the datagrid column I have an itemrendere which is an HBOX. THe Hbox contains 3 buttons Edit, Update, cancel. At first only Edit button is visible and on click of it, It is removed from the Hbox and 2 other buttons i.e. Update and Cancel are added in the Hbox. what i want is when i add these 2 buttons the size of the datagrid column should get adjusted accordingly.
I have serached a lot abt this but couldnt find a solution. Please help.
Happy new year to all.....@Pramod :
(listdata.owner as datagrid) .validateNow();
// thats wat i did. but not working.
@John : TypicalItem may work but I am using Flex Builder 3 and i think it does not provide the typicalItem class in it. -
Formatting a field before committing from editable datagrid
Hi,
I have an editable DataGrid which displays two columns, date
and value. Now, the date in the dataProvider is actually stored as
an integer (yyyymmdd) so I format it using a labelFunction to
display. I then have a custom itemEditor to set it to a date for
calling into the DateField.
The next step, and where I'm struggling, is to update the
dataProvider with an integer (yyyymmdd) calculated from the
selectedDate. Can someone please help me with how to do this?
Thanks!See the docs for data grid editing events, such as, I think,
itemEndEdit. -
Editable Datagrid from programmaticaly built XmlListCollection help needed
Hi, I am trying to build an editable datagrid with 20 empty
rows in it. Users will fill out the cells, this then gets persisted
to a DB, then later by making selections in a combobox, they can
bring this data back for viewing and/or modification. I have been
trying to create the XML dynamically and then addItem on the
XmlListCollection to no avail. Can someone please point out where I
am going wrong? Thanks!
[Bindable] private var teamGridDataAsXml:XML;
[Bindable] private var teamGridData:XMLListCollection;
private function initEmptyTeamGrid():void {
teamGridData = new XMLListCollection();
var s:String = "<rows>";
for(var i:int = 0; i < 20; i++) {
s += "<row rowIndex=\'" + i + "\' agentId='' firstName=''
lastName='' country='' />";
s += "</rows>";
teamGridDataAsXml = new XML(s);
teamGridData.addItem(teamGridDataAsXml);
<mx:DataGrid id="agentInfo" editable="true"
dataProvider="{teamGridData}" width="100%" height="100%"
rowCount="20">
<mx:columns>
<mx:DataGridColumn headerText="#" dataField="@rowIndex"
editable="false"/>
<mx:DataGridColumn headerText="Agent ID"
dataField="@agentId" editable="true"/>
<mx:DataGridColumn headerText="First Name"
dataField="@firstName" editable="true"/>
<mx:DataGridColumn headerText="Last Name"
dataField="@lastName" editable="true"/>
<mx:DataGridColumn headerText="Country"
dataField="@country" editable="true"/>
</mx:columns>
</mx:DataGrid>teamGridDataAsXml = new XML(s);
trace(teamGridDataAsXml.toXMLString() ); to be sure you have
good xml
var xlRows:XMLList = teamGridDataAsXml.row;
trace(xlRows.length()); //what you expect?
teamGridData =new XMLListCOllection(xlRows);
You could skip the xml variable and go straignt into the
XMLListCollection also. In the loop, build the XML node, using XML
literal syntax, and then call addItem *inside the loop*.
Tracy -
Editable Datagrid with LabelFunction Problems
Hi,
I'm having problems with a datagrid with editable columns and labelFunctions.
The problem is that when i leave the editable field by a way that wasnt with Escape Key, the datagrid apply again the labelFunction and destroy the number formattion adding a lot of numbers.
When the field is filled with 0000,00 he just adds more zeros, like 0.000.000,0000 and keep going after do the same process.
And when the field has a number different of zero, he apply the labelFunction then after he remove the labelFunction. After few times it just make the number vanish and the cell goes empty.
I read the documentation about editing cell and tryed to implement a solution to prevent the cell be edited, without sucess.
The source code goes attached for some advice on my problem.
Thanks, Fredy.Hi,
I solved a part of problem with some changes that i've made.
Now there is no problem with values different of zero, when i got just number, its fine, but still have problems with zero values.
The snippet code goes next, the bold part that was modified from the last sample.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
backgroundColor="white">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.DataGridEventReason;
import mx.controls.TextInput;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.formatters.NumberFormatter;
import mx.events.DataGridEvent;
import mx.collections.ArrayCollection;
[Bindable] private var collection:ArrayCollection = new ArrayCollection([
{code:1, description:"Item 1", value:4564654},
{code:2, description:"Item 2", value:00000000},
{code:3, description:"Item 3", value:00000000},
{code:4, description:"Item 4", value:00000000},
{code:5, description:"Item 5", value:00000000},
{code:6, description:"Item 6", value:00000000},
{code:7, description:"Item 7", value:00000000}
private var formatter:NumberFormatter;
private function formatterFunction(item:Object, column:DataGridColumn):String {
if (formatter == null){
formatter = new NumberFormatter();
formatter.decimalSeparatorTo = ",";
formatter.thousandsSeparatorTo = ".";
formatter.decimalSeparatorFrom = ",";
formatter.thousandsSeparatorFrom = ".";
formatter.useThousandsSeparator = true;
formatter.precision = 4;
return formatter.format(item[column.dataField]);
private function editEndHandler(event:DataGridEvent):void {
var myEditor:TextInput = TextInput(event.currentTarget.itemEditorInstance);
var newVal:Number = isNaN(Number(myEditor.text)) ? myEditor.text as Number : 0.0000;
var oldVal:Number = Number(event.currentTarget.editedItemRenderer.data[event.dataField]);
// it solves the partial part of the problem, but still have some errors
if (event.reason == DataGridEventReason.CANCELLED || event.reason == DataGridEventReason.OTHER) {
return;
if (oldVal == newVal ) {
// i've tryed this, but the itemEditor still open
event.preventDefault();
// if I just put 'return', still have the same problem
// return;
]]>
</mx:Script>
<mx:Label text="Bug datagrid editavel com labelFunction"
fontSize="16"
fontWeight="bold" />
<mx:DataGrid dataProvider="{collection}"
editable="true"
itemEditEnd="editEndHandler(event)">
<mx:columns>
<mx:DataGridColumn headerText="Código"
dataField="code"
editable="false"/>
<mx:DataGridColumn headerText="Descrição"
dataField="description"
editable="false"/>
<mx:DataGridColumn headerText="Valor"
width="300"
dataField="value"
labelFunction="formatterFunction"
editable="true"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
@Alex
Thanks for the answer.
I want to edit this column, but if there is no 'change' i dont want to apply again the label function and close the itemEditor.
I've tryed to call event.preventDefault() but i dont know what to do next.
Do you have some advice how to solve my problem?
This is just happening when i got zero values on my datagrid =/
Thanks all for the answers. -
ErrorTemplate on editing datagrid
Hello,
I'm trying to create a MVVM application to register purchases.
I have ViewModel composed by :
Purchase
Products (return collection of products of the Purchase(Purchase.products)
ProductToAdd (this is a product to add to the Purchase via button)
Implement IDataErrorInfo to validate the order and the products collection
I created a collection of error to validate the ProductToAdd on button click.
So if there is an error on ProductToAdd the product is not add to the collection and the textbox with error become Red.
The value of each product of the purchase can be updated in the datagrid.
My problem is : When i update value in DataGrid the cell updated didn't get errorTemplate when is there an error.
My sample is the following : http://www.filedropper.com/validationexample_3
I didn't know how can i do 2 type of validation.
thanksThe Product class could implement the IEditableObject interface to keep track of whether it is currently in edit mode and then do the validation also in the setter if it is:
public class Product : IDataErrorInfo, INotifyPropertyChanged, IEditableObject
private string _Name = null;
[Required(ErrorMessage = "Nom is required")]
public string Name
get
return _Name;
set
_Name = value;
if (_isInEditMode) {
Validate();
RaisePropertyChanged("Name");
private int? _Quantity = null;
[Required(ErrorMessage = "Quantity is required")]
[Range(1, 9, ErrorMessage = "Quantity must be superior to 0 and inferior to 10")]
public int? Quantity
get
return _Quantity;
set
_Quantity = value;
if (_isInEditMode) {
Validate();
RaisePropertyChanged("Quantity");
public Dictionary<string, string> _errors = new Dictionary<string, string>();
public bool Validate()
_errors["Name"] = Validateurs.Courant.GetErreur(this, "Name");
_errors["Quantity"] = Validateurs.Courant.GetErreur(this, "Quantity");
RaisePropertyChanged("Name");
RaisePropertyChanged("Quantity");
if (_errors["Name"] != "" || _errors["Quantity"] != "")
return true;
return false;
#region INotifyPropertyChanged
public void RaisePropertyChanged(string propertyName)
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region IDataErrorInfo
public string Error
get
throw new NotImplementedException();
public string this[string columnName]
get
if (_errors.ContainsKey(columnName))
return _errors[columnName];
return null;
#endregion
#region IEditableObject Members
private bool _isInEditMode;
public void BeginEdit() {
_isInEditMode = true;
public void CancelEdit() {
_isInEditMode = false;
public void EndEdit() {
_isInEditMode = false;
#endregion
To remove the red exclamation mark that may get stuck in the row header even if you type in a valid value in the cell, you could use the following RowStyle:
<DataGrid Width="477" Height="200" Canvas.Left="10" Canvas.Top="157"
ItemsSource="{Binding products}" AutoGenerateColumns="False">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="ValidationErrorTemplate" Value="{x:Null}"/>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
Please refer to the following thread for more information about this:
http://stackoverflow.com/questions/5099039/wpf-datagrid-validation-errors-not-clearing
And remember to mark helpful posts as answer and to start a new thread if you have a new question. -
DataGrid Column Focus Out Event
I have an editable datagrid and I'm trying to accomplish the
following:
When a user edits a cell, then focuses out, a function is
called that sends off a service with that value, along with the id
value in that same item. I've tried using itemFocusOut, but I'm
getting bizzare results---the function is executing multiple times.
So i need the function to know what cell was focused out, and also
all of the other information that accompanies that item.
Thanks for any help.Here's what I ended up doing.
Somewhere after Load, I added:
PropertyDescriptor pd = DependencyPropertyDescriptor.FromProperty(DataGridColumn.ActualWidthProperty, typeof(DataGridColumn));
foreach (DataGridColumn column in Columns) {
//Add a listener for this column's width
pd.AddValueChanged(column, new EventHandler(ColumnWidthPropertyChanged));
Then the following 2 methods:
private bool _columnWidthChanging;
private void ColumnWidthPropertyChanged(object sender, EventArgs e)
// listen for when the mouse is released
_columnWidthChanging = true;
if (sender != null)
Mouse.AddPreviewMouseUpHandler(this, BaseDataGrid_MouseLeftButtonUp);
void BaseDataGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
if (_columnWidthChanging) {
_columnWidthChanging = false;
/// whatever you wanted to do here
The ColumnWidthPropertyChanged fires constantly while the user drags the width around, so if you just listen to that, you'll be over-doing it.
Adding the PreviewMouseUp handler let me only do my processing when the user is done changing the width.
Hope this helps someone.
Janene -
Hi,
Is there any way to validate datagrid column or cell.
Please help
Thanks
Kumarquote:
Originally posted by:
peterent
Follow Tracy's advice, but also handle the itemEditEnd event.
In that event handler you can find if the data passed validation.
If it fails you can cancel the edit.
Look up itemEditEnd in the Flex 2 docs.
Maybe you are looking for
-
Can you trade in your iPad for another one???.......... If you can would you get your money back?????
-
How do i add section on page to the beginning of a document
i have finished a pages document but i need to add a new section at the beginning of the document how do i do this? and how do i flatten my document so everything in anchored down and not moving
-
LR 1.3.1 suddenly will not open
For unknown reasons, LR 1.3.1 will not open under Win Vista. The error screen "Microsoft Visual C ++ Runtime Error" appears with the dialogue "This operation has requested the Runtime to it in an unusual way". Using the Restore command produced no su
-
Dimension table and fact table exists data physically
Hi experts, can anyone plz tell me weather dimension table and fact table exists data physically or not/
-
How to view photos in iPhoto on iPad 2
I've got a MacMini running Snow Leopard. I've got iPhoto on it with numerous photos. They are shared on my home network and I can view them on my AppleTv's. I want to be able to use my iPad to view the photos, just like I can view them using my Ap