I have class say class A and i have cintialised a list (I am using HashSet
) in the costructor so as to have its access throught out the program.
I Add the item in the list inside the Loaded event of comboBox. Ans i use that saved list after the loaded event I found that it do not contain the data i added.
Is this thing normal with loaded event ? Could some one please tell me way to save data added inside the List (I am using HashSet
) in loaded event?
My code is :
static HashSet < string > listOfUpdatedUIElement = new HashSet < string > ();
static HashSet < string > storeUpdatedUIElement = new HashSet < string > ();
//This in constructor
GenerateParametersPreview()
{
storeUpdatedUIElement = null;
}
public Grid simeFunction() {
ComboBox cmb = new ComboBox();
cmb.Loaded += (o3, e) => {
foreach(string atrb in listOfUpdatedUIElement) //I have seen on debugging the data are updated in listOfUpdatedUIElement
{
storeUpdatedUIElement.Add(atrb);
}
};
foreach(string atrb in storeUpdatedUIElement) //Here storeUpdatedUIElement hashset contains nothing inside
{
cmb.Items.Add(atrb);
}
Grid.SetColumn(cmb, 1);
comboRowGrid.Children.Add(cmb);
Grid.SetRow(comboRowGrid, 0);
bigGrid.Children.Add(comboRowGrid); //suppose ihad created this bigGrid and it will dispaly my comboBox
return (bigGrid);
}
The events are the main tool of the Event-driven-programming paradigm.
In event driven programming you are not sure when and whether at all some condition changes (like some ComboBox is finally loaded or not), you are reacting to the notification about that change - raised event.
It means that
cmb.Loaded += (o3, e) =>
{
foreach(string atrb in listOfUpdatedUIElement)//I have seen on debugging the data are updated in listOfUpdatedUIElement
{
storeUpdatedUIElement.Add(atrb);
}
};
won't(at least it is hardly possible) execute before the
foreach(string atrb in storeUpdatedUIElement) //Here storeUpdatedUIElement hashset contains nothing inside
{
cmb.Items.Add(atrb);
}
That's why the storeUpdatedUIElement
is empty when the loop enumerates it.
SOLUTION:
So, if you want to update your ComboBox
items on Loaded
event you should put all the relevant code inside the event:
cmb.Loaded += (o3, e) =>
{
foreach(string atrb in listOfUpdatedUIElement)//I have seen on debugging the data are updated in listOfUpdatedUIElement
{
storeUpdatedUIElement.Add(atrb);
}
foreach(string atrb in storeUpdatedUIElement) //Here storeUpdatedUIElement hashset contains nothing inside
{
cmb.Items.Add(atrb);
}
};
P.S.: In such a case you should probably unite those two loops in one:
foreach(string atrb in listOfUpdatedUIElement)//I have seen on debugging the data are updated in listOfUpdatedUIElement
{
storeUpdatedUIElement.Add(atrb); // Remove it too if it is not used anywhere else
cmb.Items.Add(atrb);
}