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 Answers1

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";
dotnetom
  • 24,551
  • 9
  • 51
  • 54
  • 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? – Kamyar Mirzavaziri Sep 18 '16 at 11:36
  • I found the answer ([Here](http://stackoverflow.com/questions/11395315)). Thank you for your answer. :) – Kamyar Mirzavaziri Sep 18 '16 at 21:16