Search code examples
c#winformstrackbar

increase pen width with trackbar value


As the it's said in the title, i am trying to increase pen width size by using a trackbar. This is what i have written so far:

public partial class Form26_10 : Form
    {
        float scrollValue = 0F;

        Pen CustomPen = new Pen(Color.Black, scrollValue);//ERROR<-

        public Form26_10()
        {
            InitializeComponent();

        }

     private void trackBar1_Scroll(object sender, EventArgs e)
    {
        scrollValue = trackBar1.Value;
    }

}

essentially i should be able to declare a value in memory, then have it in the pen width parameter and so when the trackbar value change's the pen width changes. Though i am getting this error:

a field initializer cannot reference the non-static field, method or property of 'Form.scrollValue' 

Solution

  • public partial class Form26_10 : Form
    {
        private Pen CustomPen;
    
        public Form26_10()
        {
            InitializeComponent();
            CustomPen = new Pen(Color.Black, scrollValue);
        }
    
        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            CustomPen.Width = trackBar1.Value;
        }
    }
    

    You shouldn't initialize class fields at declaration if you've got a changing value. Also, float has a default value of 0.0F so you don't need to initialize it. I removed it in this example because I assumed you wouldn't need it. If you still plan on using it, you can just add it at the top.

    float scrollValue;