Click to See Complete Forum and Search --> : [RESOLVED] Need my Function available for two Items


bixel
February 19th, 2009, 04:14 PM
C# VS 2008

I have a function that is doing some necessary stuff depending on the values set in a numericUpDown. The function is triggered by a combobox selection. example


private void ChangeLevels(object sender, EventArgs e)
{
decimal valueSet = numeric_Levels1.Value;
if (newValue == 0)
{
Do STUFF
}
else if (newValue > 0)
{
Do STUFF
}


in Forms I understand that function can be assign to multiple tools, however in this case I want a 2nd set of numericUpDown and a combobox using the same function but be independant of the 1st set. As you can see in the code if I dropped this function in the 2nd set of comboxes it would still be using the 1st numericUpDown. Is there a way I can make this code 'universal' with out duplicating it?

Arjay
February 19th, 2009, 05:32 PM
It's a bit tough to follow your code - did you mean to the valueSet variable called newValue or is newValue a class field? (as a side issue always a good reason to preface class fields with an underscore).

At any rate, if we assume decimal valueSet should have been named newValue. Just pull out the code that does stuff into another method.

private void ChangeLevels(object sender, EventArgs e)
{
SetStuff( numeric_Levels1.Value );
}

private void ChangeMoreLevels(object sender, EventArgs e)
{
SetStuff( numeric_Levels2.Value );
}

private void SetStuff( decimal value )
{
if ( value == 0)
{
// Do STUFF
}
else if (value > 0)
{
// Do other STUFF
}
}

bixel
February 19th, 2009, 06:21 PM
That's perfect! (I prolly would have figured it out on my own but I am still waking up). need moar coffee!!

Mutant_Fruit
February 19th, 2009, 06:23 PM
private void ChangeLevels(object sender, EventArgs e)
{
decimal valueSet = ((NumericUpDown) sender).Value;
if (newValue == 0)
{
Do STUFF
}
else if (newValue > 0)
{
Do STUFF
}

Or just use 'sender' the way it was meant to be used ;)

cjard
February 19th, 2009, 06:24 PM
I cant work out your problem but this may help:

Suppose I had 10 buttons on a form. I wanted to use one block of code to handle them all. I Link them all to the same handler, then:



public void Generic_Click(object sender, ClickEventArgs e){

MessageBox.Show((sender as Button).Text);

MessageBox.Show("The object stored in this button's tag is: " + (sender as Button).Tag.ToString());

}


This is one block of code that will display a different text depending which button was clicked

Perhaps this is what you mean?

cjard
February 19th, 2009, 06:25 PM
One minute, darnit

Mutant_Fruit
February 19th, 2009, 06:29 PM
Purely a style point:

(sender as Button).Text

Never use 'as' unless you follow it by a null check. If things are going to fail, it's *much* better to fail with an InvalidCastException than it is a NullReferenceException.


One minute, darnit

That's what she said!

oh.. wait. That's not a good thing :(