1

I'm making a c# windows app and trying to create objects in form (for example TextBox and Label) programmatically. And I can do this easily but I can't define them as public objects. I have a function called 'makeTextBox(...)' in a class called 'varstats' and this is the function:

public static void makeTextBox(Panel pnlMain, int offsetTop, int offsetRight, string strName = "")
    {
        TextBox txt = new TextBox();
        txt.Name = strName;
        txt.Parent = pnlMain;
        txt.AutoSize = true;
        txt.Width = (pnlMain.Width - 9 * defdis) / 3; //defdis is a public int and means default distance
        txt.Location = new Point(pnlMain.Width - txt.Width - defdis - offsetRight - 3, offsetTop + defdis);
    }

And this is my main form code in form load:

 varstats.makeTextBox(pnlMain, 0, 0, "txtCustName");

This function works very correctly (:D) and I can see the TextBox in my Panel, but how can I access the TextBox? for example in another form I need to read the text property of TextBox and save it to my database? how to do this?

Note that I can't define them in header of my class because I want to make too many objects using for or while and also I want to remove them and make some another objects in some cases.

1 Answer 1

1

Simplest approach is to return textbox from your method and then use it:

// return is changed from void to TextBox:
public static TextBox makeTextBox(Panel pnlMain, int offsetTop, int offsetRight, string strName = "")
{
    TextBox txt = new TextBox();
    txt.Name = strName;
    txt.Parent = pnlMain;
    txt.AutoSize = true;
    txt.Width = (pnlMain.Width - 9 * defdis) / 3; //defdis is a public int and means default distance
    txt.Location = new Point(pnlMain.Width - txt.Width - defdis - offsetRight - 3, offsetTop + defdis);

    // return the textbox you created:
    return txt;
}

And now you can assign the return value of a method to a variable and use it any way you want:

TextBox myTextBox = varstats.makeTextBox(pnlMain, 0, 0, "txtCustName");

// for example, change the text:
myTextBox.Text = "Changed Text";
Sign up to request clarification or add additional context in comments.

2 Comments

It's good idea but I have another function called preparePanel and this function make too many controls with different types (TextBox, Label, DataGridView, ...) and this function use the functions makeLabel and .... and I should return an array of different controls in my preparePanel function. is it possible to have such an array?
I found the answer (Here). Thank you for your answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.