CodeMonkey36
CodeMonkey36

Reputation: 11

How do I pass a Windows Form control to a class I created?

I created class that has a Control property. The idea being that this class will sit in a list and the control is tied to that instance of the class. I can't however for the life of me figure out why the Property wont accept any values. Here is how I constructed the Property:

    public Control LinkedControl
    {
        get
        {
            return aControl;
        }
        set
        {
            aControl = value;
        }
    }

This only results in the property receiving a value of "" when I try to assign a control.

My attempt to assign the control follows as:

    aClass.LinkedControl = txtTextBox;

as well as

    aClass.LinkedControl.Equals(txtTextBox);

This results in no error, but nothing comes through to the class.

What am I doing wrong?

EDIT: Basically what I am trying to achieve here is that instead of a property of the textbox being stored, like textbox.text, I want to rather store an instance of the textbox itself in the class. This is in a list<> based program and the storing of the textbox instance is the reference tool.

Upvotes: 1

Views: 235

Answers (3)

Amit Mittal
Amit Mittal

Reputation: 1127

If you are getting a "" this means your code is working just fine. Since a Control is of Reference Type, receiving a "" indicates that the control txtTextBox is currently empty.

Trying typing something in txtTextBox and try to access aClass.LinkedControl.Text and see if you get the same string as typed in txtTextBox.

And by the way, you must be receiving a "" from the txtTextBox.Text and not from txtTextBox. txtTextBox.Text is a string while txtTextBox is a control.

Upvotes: 0

Mat
Mat

Reputation: 2072

Maybe your'e passing a null value? You can check by set breakpoint in your property setter to check what value is passed.

You maybe also wnat to have a look at the tag property of a control. This is the other way around --> you assign a object to the control. which works very well for lists (such as combobox, listview,etc.).

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag(v=vs.110).aspx

Also Datbinding via a bindingsource could help you out for you general design: https://www.google.com/search?q=tag+c%23+property&sourceid=ie7&rls=com.microsoft:de-at:IE-SearchBox&ie=&oe=&safe=vss#q=windows+forms+bindingsource+tutorial&rls=com.microsoft:de-at:IE-SearchBox&safe=vss

Upvotes: 1

Steven Evers
Steven Evers

Reputation: 17196

A couple things:

  1. In the form you'll need to add the control to some UI element (like a panel or something). You can do this in your setter.
  2. You might need to repaint (invalidate) the form to force the control to draw.

Upvotes: 0

Related Questions