Ajay Chorge
Ajay Chorge

Reputation: 23

How to access asp controls in a class file

I have created a panel in my page view (tour.aspx file). Now I want to access it in my class file (add_tour.cs file).

This is my panel:

<asp:Panel ID="itinerary_panel" runat="server"></asp:Panel>

This is my code behind tour.aspx file:

add_tour tour_obj = new add_tour();
int days_count = 2;
tour_obj.textbox_generator(days_count);

And this code is in add_tour.cs file:

public void textbox_generator(int days_count)
{

}

Now how to access the panel from aspx file? Please help.

Upvotes: 1

Views: 389

Answers (2)

mason
mason

Reputation: 32738

If you really wanted your other class to itself add the controls directly to the panel, then you would just pass a reference to the panel from the code behind to the class.

public void textbox_generator(int days_count, Panel panel)
{
    for(int i = 0; i < days_count; i++)
    {
        txt_desc = new TextBox();
        txt_desc.ID = "txt_desc" + i.ToString();
        txt_desc.CssClass = "form-control";
        txt_desc.Attributes.Add("placeholder", "Enter day " + i + " description");
        txt_desc.TextMode = TextBoxMode.MultiLine;
        panel.Controls.Add(txt_desc);          
    }
}

and call this this way from your code behind:

add_tour tour_obj = new add_tour();
int days_count = 2;
var textBoxes = tour_obj.textbox_generator(days_count, itinerary_panel);

This works because itinerary_panel actually is a reference to the panel. See Passing Objects By Reference or Value in C#. However, it's often a bad idea to have a method modify the state in that manner.

Upvotes: 1

mason
mason

Reputation: 32738

There's no need to actually add the text boxes to the panel from this class.

public List<TextBox> textbox_generator(int days_count)
{
    var textBoxes = new List<TextBox>();

    for(int i = 0; i < days_count; i++)
    {
        txt_desc = new TextBox();
        txt_desc.ID = "txt_desc" + i.ToString();
        txt_desc.CssClass = "form-control";
        txt_desc.Attributes.Add("placeholder", "Enter day " + i + " description");
        txt_desc.TextMode = TextBoxMode.MultiLine;
        textBoxes.Add(txt_desc);          
    }

    return textBoxes;
}

Then change your code behind to:

add_tour tour_obj = new add_tour();
int days_count = 2;
var textBoxes = tour_obj.textbox_generator(days_count);
foreach(var textBox in textBoxes)
{
    itinerary_panel.Controls.Add(textBox);
}

Note that you need to be careful where you add these controls in the page lifecycle. See Microsoft documentation.

This keeps your textbox_generator from needing to know anything about the specific page using it.

Also, you should really align your naming conventions with C# standards. Use PascalCasing. textbox_generator should be TextBoxGenerator etc. And you can probably make textbox_generator into a static method if it doesn't need to access any fields or properties of its class.

Upvotes: 1

Related Questions