[RESOLVED] Need my Function available for two Items
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
Code:
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?
Re: Need my Function available for two Items
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.
Code:
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
}
}
Re: Need my Function available for two Items
That's perfect! (I prolly would have figured it out on my own but I am still waking up). need moar coffee!!
Re: [RESOLVED] Need my Function available for two Items
Code:
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 ;)
Re: [RESOLVED] Need my Function available for two Items
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:
Code:
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?
Re: [RESOLVED] Need my Function available for two Items
Re: [RESOLVED] Need my Function available for two Items
Purely a style point:
Code:
(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.
Quote:
One minute, darnit
That's what she said!
oh.. wait. That's not a good thing :(