Search code examples
c#class-library

Load Form in Class Library with pre-defined values C#


I'm going to explain this as best I can. I have a form designed into a class library and I make it visible in the middle of the code. When I do this, I want to populate the textboxes with pre-determined values. let's say I want the varaibles color1 and color2 to populate the textboxes. How do I call these variables to when the form loads? None of the textboxes appear in visual studio as I type them...

string color1 = 'blue'; string color2 = 'red';

textbox1.text = color1 textbox2.text = color2

InspectionForm myForm = new InspectionForm();
                        myForm.Visible = true;

...

private void InspectionForm_Load(object sender, System.EventArgs e)
        {
        }

Solution

  • You can make a constructor on your form

    public InspectionForm(string color1, string color2)
    {
        InitializeComponent(); //This is may or may not be needed
        textBox1.Text = color1;
        textBox2.Text = color2;
    }
    

    Or make a public method to set your values from.

    public void SetColors(string color1, string color2)
    {
        textBox1.Text = color1;
        textBox2.Text = color2;
    }
    

    Then use them like so:

    var form = new InspectionForm("blue", "red");
    //or
    var form = new InspectionForm();
    form.SetColors("blue", "red");
    

    However, If you are not able to change the class library, you won't really have any options outside of some reflection hackery.