Sign in to follow this  
dhammer

C# Collections (Obj to Numericupdown convertions)

Recommended Posts

dhammer    122
I'm looking for a means to create a collection of numericupdown objects and then easily extract their properties (Value and Name) by using a Foreach loop which will cycle through each object in the collection. Right now I'm using ArrayList because it stores objects pretty easily but I'm having trouble pulling my information out of it after the fact. I end up pulling a Object out of the ArrayList but can't seem to convert it back to NumericUpDown type in order to view the Value and Name properties of that object. This is the code that i am having trouble with. The line, "n_UpDn = obj; is obviously an improper convertion from object to numericupdown.
[source=lang="c#"]
StringBuilder stats = new StringBuilder();
NumericUpDown n_UpDn;

//Stat_Objs is an ArrayList with NumericUpDns added to it
foreach (Object obj in Stat_Objs)
{
    n_UpDn = obj;
    if (n_UpDn.Value > 0)
        stats.Append(n_UpDn.Name.ToString() + "+" + n_UpDn.Value.ToString()):
}

Share this post


Link to post
Share on other sites
Scet    960
You need to do a cast, "n_UpDn = (NumericUpDown)obj;".

However if you have access to .Net 2.0 or above, the use of "Object" is considered bad practice. You should be using a generic List(System.Collections.Generic.List) instead of an ArrayList.

Share this post


Link to post
Share on other sites
TheTroll    883
Two better ways.


// This works with .Net 2.0 and above.
// First use List instead of a list array. This just shows you the list.
List<NumericUpDown> Stat_Objs = new List<NumericUpDown>();

// Then your stuff with a few changes.
StringBuilder stats = new StringBuilder();

// You don't need this any more.
// NumericUpDown n_UpDn;

foreach (NumericUpDown n_UpDn in Stat_Objs)
{
n_UpDn = obj;
if (n_UpDn.Value > 0)
stats.Append(n_UpDn.Name.ToString() + "+" + n_UpDn.Value.ToString()):
}





// Now if you are stuck with .Net 1.x or still want to use the ArrayList you can do this.
StringBuilder stats = new StringBuilder();

//We still don't need this.
//NumericUpDown n_UpDn;

//The foreach loop actually does the cast for you. So you don't need to treat it as an "object".
foreach (NumericUpDown n_UpDn in Stat_Objs)
{
n_UpDn = obj;
if (n_UpDn.Value > 0)
stats.Append(n_UpDn.Name.ToString() + "+" + n_UpDn.Value.ToString()):
}




theTroll

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this