Access to color variable in a class

A

Anonymous

Hi,
I have the following code. ( Sorry if it is a little rough or improperly
written ).

<########## CODE BEGIN ##########>

public class TestClass : System.Windows.Forms.UserControl
{
public TestClass( ref Color InputColor )
{
Button btn1 = new Button();
btn1.Text = "Button";
btn1.Click += new System.EventHandler( btn1_Click );
this.Controls.Add( btn1 );
}

private void btn1_Click( object sender, EventArgs e )
{
}
}

<########## CODE END ##########>

I wish to change 'InputColor' in the button click event handler, but if I
try to change 'InputColor' with the above code it fails to compile with an
error similar to "InputColor does not exist in the class or namespace blah
blah". Sure, I can understand that, however, can you please advise me of the
best way to achieve what I have described.
Thank you for any help.
 
D

DalePres

I've modified your code slightly. You need to have a class level field in
order to expand the scope of InputColor. You can assign the ref value of
InputColor to the field because it creates a shallow copy so when you modify
inputColor, as long as you don't use "new" or some method that creates a new
color rather than assigns a color, your change will show up in InputColor.

Dale


public class TestClass : System.Windows.Forms.UserControl
{
private Color inputColor;
public TestClass( ref Color InputColor )
{
inputColor = InputColor;
Button btn1 = new Button();
btn1.Text = "Button";
btn1.Click += new System.EventHandler( btn1_Click );
this.Controls.Add( btn1 );
}

private void btn1_Click( object sender, EventArgs e )
{
//Change the inputColor value here.
}
}
 
C

C# Learner

Anonymous said:
Hi,
Unfortunately this does not appear to be working. I have written and
attatched ( in code form ) a small application to demonstrate the behaviour.
The application has a panel and 2 buttons. The panel starts off as being
yellow. My user control has a button which attempts to change the referenced
color to red. The button on the main form attempts to change the color of
the panel via the referenced color 'PanelColor'.
When I run the application it is clear that the referenced color is not
being changed in the way that I expect.

Thank you for your help.

What you're trying wouldn't work for several reasons. You'd have to
do something similar to the following instead.

public class TestClass : System.Windows.Forms.UserControl
{

private Panel myPanel;

public TestClass(Panel p)
{
myPanel = p;
}

private void TurnPanelRedButton_Click( object sender, EventArgs e )
{
myPanel.BackColor = Color.Red;
}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top