KamyarM KamyarM - 2 months ago 15
C# Question

how to access an object which made with a function in c#

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.

Answer

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";