C# How to access Controls on a winform?

Hi

I'm moving a C# Console app to a winforms so I can access user controls easier

I'm confused why I get this error

Severity      Code      Description      Project      File      Line      Suppression State
Error      CS0120      An object reference is required for the non-static field, method, or property 'Form1.AltCheckBox'      PathTo\\MyApp\Form1.cs      97      Active

I originally created a library class to hold the functions in but that gave the same error so I moved the function inside the form section    

The code bellow is only to illustrate

Why Can I access the form controls in 1 function  and not the other and how do I move these into a separate library?

	namespace MySpace
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        

        private void PasteButton_Click(object sender, EventArgs e)
        {
             //  #### This works
            if (Clipboard.GetDataObject().GetDataPresent("System.String") == true)
            {
                URLTextBox.Clear();
                URLTextBox.Paste();
            }
            else
            {
                MessageBox.Show("Only Text Please!");
            }
        }
        private static string FindImg(string url)
        {
                       //#### Error Here ####
    			if (AltCheckBox.Checked)
    			{
    				// Do Stuff
    			}
                       else
    			{
    				// Do other Stuff
    			}
                    return aString;
             }	
		}

	}

Open in new window

LVL 1
trevor1940Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MishaProgrammerCommented:
You call a non static property from a static method. You will need to either make the property static, or mske your method non static!
For example,
  private string FindImg(string url)
{
/// your code!
}

Open in new window

0
trevor1940Author Commented:
Hi that worked in it's current location  but when I moved it to a Library class I get

Severity      Code      Description      Project      File      Line      Suppression State
Error      CS0103      The name 'AltCheckBox' does not exist in the current context      PathTo\\MyLibrary.cs      46      Active
0
MishaProgrammerCommented:
May be your library "dont know" about this Form and this Form's control (AltCheckBox).
Do you add link to this project with AltCheckBox in your library?
And do you create an instance of Form ?
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

trevor1940Author Commented:
Erm!

I have a Form named Form1 on it there is a CheckBox  named AltCheckBox

In solutions  explorer I right Clicked the project => Add Item => class Named MyAppLibrary.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Text.RegularExpressions;

using System.Web;
using System.Net;
using System.IO;
using HtmlAgilityPack;


namespace MyApp
{
    class MYAppLibrary
    {
        private string FindImg(string url)
          {
             /// Pasted code here

           }
     }
}

Open in new window

1
MishaProgrammerCommented:
I thought, that you create library project....
 
private string FindImg(string url)
          {
               Form1 myForm = new Form1;
            if (myForm.AltCheckBox.Checked)
            {
                   // do something
            }
           }

Open in new window


But this method is some bad. In this new instance state of all controls is default. If you want to manage something whiht Form's controls
information,  pass  control state, for example:
private string FindImg(string url, bool AltCheckBoxState)
          {
            if (AltCheckBoxState)
            {
                   // do something
            }
           }

Open in new window


And calling this method:
 private void PasteButton_Click(object sender, EventArgs e)
        {
          MYAppLibrary mylib = new  MYAppLibrary ();
          mylib.FindImg(URL_Value,AltCheckBox.Checked );
        }

Open in new window

0
trevor1940Author Commented:
Ok I think I understand

So what ever button / checkbox etc on the form has to pass an argument to the function!

What happens when you pass the CheckBox state but need to read or write to a Text box?

Are you saying you have to pass the value back to the calling control for it to change another form control?
0
trevor1940Author Commented:
Also

What happens if  Function B access the form control but is called by Function A?
0
MishaProgrammerCommented:
1) You can pass checkbox  state and text from TextBox when user click button. Do you ask about it?
2) I give example how pass value to library (class) from Form. But I don`t khow what purpose you pursue.
It is not bad to pass values (strging, bool) from form to library.
Also you can create static method in your library.

private static string FindImg(string url, bool AltCheckBoxState)
          {
             /// Pasted code here

           }
/.............................../
 private void PasteButton_Click(object sender, EventArgs e)
        {
          MYAppLibrary.FindImg(URL_Value,AltCheckBox.Checked);
        }

Open in new window


Static method is also good. Their shortcomings - if you want to call method "PasteButton_Click" in other place, you should make this method static too.
0
MishaProgrammerCommented:
"What happens if  Function B access the form control but is called by Function A? "

Do  you call method B, which call methodA, which chande form ?
In this case state of controls will be changed. May be I don`t understad your question?
0
trevor1940Author Commented:
Within the original console app the flow line works
This is difficult to explain

I think what I need to do is create a smaller test app and experiment with passing / accessing form controls to and from class functions

Do you know of any online examples that do this?
0
MishaProgrammerCommented:
If I correct understand you, there is this article, for example
https://www.c-sharpcorner.com/article/how-to-pass-control-values-between-windows-forms/
0
trevor1940Author Commented:
Not really but I'm sure I'll need it in the future.

From what you've told me I've created a new simple Demo
When click button1 it calls GetText()

GetText checks the Checkbox and returns a greeting which is written to the firstNameTextBox

Form1.JPG
Form1.cs
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    interface iForm
    {
        string FirstName { get; set; }
        bool IsChecked{get; set;}
      // repeat for every form control  that need accessing or chaging
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public string FirstName
        {
            get { return firstNameTextBox.Text; }
            set { firstNameTextBox.Text = value; }
        }
     
        private void button1_Click(object sender, EventArgs e)
        {
            string Txt = GetText();
            FirstName = Txt;
        }


    }
    
}

Open in new window


Class1.cs added as a separate class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    class Class1
    {
        private readonly iForm form;
        public Class1(iForm form)
        {

            this.form = form;
            form.FirstName = "Trevor";

        }

        private string GetText()
        {
            string greeting = "";
            if (form.IsChecked == true)
            {
                greeting = "Hello " + form.FirstName;
            }
            else
            {
                greeting = "Goodbye " + form.FirstName;
            }
            return greeting;
        }

    }
}

Open in new window


This isn't working not sure why?

Is this how you access form control from a separate class file?
0
MishaProgrammerCommented:
You call method "GetText" of class "Class1"
in class "Form1".
How does class Form1 know about this method?
I see two solutions, which I try to tell before.
1) create instance of Class1 and call this method
2) make this method static.
If I correct understand you...
0
trevor1940Author Commented:
Hi
I can't test this until this evening but do you mean like this?

where  "Class1" is the name of the class where GetText(); is

 private void button1_Click(object sender, EventArgs e)
        {
           Class1 mylib = new Class1();
           string Txt = mylib.GetText();
           FirstName = Txt;
        }

AND


        private static  string GetText()
        {
            string greeting = "";
            if (form.IsChecked == true)
            {
                greeting = "Hello " + form.FirstName;
            }
            else
            {
                greeting = "Goodbye " + form.FirstName;
            }
            return greeting;
        }

Open in new window

0
MishaProgrammerCommented:
Yes, but
Class1 myLib = new Class1 (this); 

Open in new window

Pass form class as parameter to Class1.
0
trevor1940Author Commented:
Hi Sorry to keep bothering you

I've made the changes you suggested but get 5  errors

Form1.cs
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    interface iForm
    {
        string FirstName { get; set; }
        bool IsChecked{get; set;}
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public string FirstName
        {
            get { return firstNameTextBox.Text; }
            set { firstNameTextBox.Text = value; }
        }
     
        private void button1_Click(object sender, EventArgs e)
        {
            Class1 myLib = new Class1 (this); 
            string Txt = GetText();
            FirstName = Txt;
        }


    }
    
}

Open in new window


Class1.cs added as a separate class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    class Class1
    {
        private readonly iForm form;
        public Class1(iForm form)
        {

            this.form = form;
            form.FirstName = "Trevor";

        }

        private static string GetText()
        {
            string greeting = "";
            if (form.IsChecked == true)
            {
                greeting = "Hello " + form.FirstName;
            }
            else
            {
                greeting = "Goodbye " + form.FirstName;
            }
            return greeting;
        }

    }
}

Open in new window


Errors
Severity	Code	Description	Project	File	Line	Suppression State
Error	CS0120	An object reference is required for the non-static field, method, or property 'Class1.form'	WindowsFormsApplication1	D:\Vb\Test\WindowsFormsApplication1\WindowsFormsApplication1\Class1.cs	23	Active
Error	CS0120	An object reference is required for the non-static field, method, or property 'Class1.form'	WindowsFormsApplication1	D:\Vb\Test\WindowsFormsApplication1\WindowsFormsApplication1\Class1.cs	25	Active
Error	CS0120	An object reference is required for the non-static field, method, or property 'Class1.form'	WindowsFormsApplication1	D:\Vb\Test\WindowsFormsApplication1\WindowsFormsApplication1\Class1.cs	29	Active
Error	CS1503	Argument 1: cannot convert from 'WindowsFormsApplication1.Form1' to 'WindowsFormsApplication1.iForm'	WindowsFormsApplication1	D:\Vb\Test\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs	25	Active
Error	CS0103	The name 'GetText' does not exist in the current context	WindowsFormsApplication1	D:\Vb\Test\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs	26	Active

Open in new window

0
MishaProgrammerCommented:
You try to pass object with type Windows.Forms.Form to class Class, but your Class1 expect type iForm.
private readonly Windows.Forms.Form form;
        public Class1(Windows.Forms.Form form

Open in new window

0
MishaProgrammerCommented:
I can see, that you try to implement something like pattern MVVM , you try to separate logic of form controls and logic of business objects and processes.  
It is already exists ,for example in this article.
https://www.codeproject.com/Articles/364485/MVVM-Model-View-ViewModel-Patte
But Windows Forms not good technology for MVVM. Usually this pattern is used in Wpf.

https://www.codeproject.com/Articles/819294/WPF-MVVM-step-by-step-Basics-to-Advance-Level

I advise you to pass simple values from form controls to library class.
If you use checkBox - pass checkBox.IsChecked (bool), if you use textBox,pass textBox.Text (string)
And return strong from library class (in your example) and put this value to textBox.Text in your form class.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trevor1940Author Commented:
Hi
I got this working not sure which comment was the best help

Tank You
0
MishaProgrammerCommented:
Glad to help you!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.