How do I Add unbound columns to an Infragistics UltraGrid only once without throwing an exception?

Blanthor picture Blanthor · Feb 15, 2010 · Viewed 8.9k times · Source

With the NetVantage Windows Forms 9.1 UltraGrid, I want to add some unbound columns to do some simple calculations. The first time this code is entered in the InitializeLayout delegate, it finds that the columns don't exist yet and then adds them. Suprisingly, when I get new data, rebind the grid, and then enter this delegate again, it still finds that these columns don't exist and then tries to add them. An exception is then thrown, "Key already exists."

UltraGridColumn changeColumn, pctChgCol;

if (e.Layout.Bands[0].Columns.Contains("Change"))
{
    changeColumn = e.Layout.Bands[0].Columns["Change"];
    pctChgCol = e.Layout.Bands[0].Columns["Percent Change"];
}
else
{
    changeColumn = e.Layout.Bands[0].Columns.Add("Change");
    pctChgCol = e.Layout.Bands[0].Columns.Add("Percent Change");
}
changeColumn.Formula = "[Publish Price] - [Override Price]";
pctChgCol.Formula = "if(0=[Publish Price] , 0 , ([Publish Price] - [Override Price])/[Publish Price] )";

Answer

Blanthor picture Blanthor · Feb 22, 2010

This was an RTFM. I should have called a different method:

Change

if (e.Layout.Bands[0].Columns.Contains("Change")) 

to

if (e.Layout.Bands[0].Columns.Exists("Change")) 

The problem here is Contains checks for an object, not a key. I was checking to see if the columns collections contains a string object. Exists returns true of an object with that key is in the collection.