Run time dynamic controls in asp.net

I don’t understand that most of the developer, why they use stringbuilder to generate run time controls on page whether they know that in this case they can’t get user inserted values by using stringbuilder. So i suggest to all developers that don’t use stringbuilder for this. Please do this by using run time generating controls as per given given by example:

  1. On the aspx page use a panel for showing controls in a proper way like this and a button for saving data in

    <asp:Panel ID="pnlQuestions" runat="server" Width="100%"> </asp:Panel> <asp:LinkButton ID="lbtnNext" runat="server" CssClass="button" ToolTip="Next" OnClick="lbtnNext_Click"><span>Save & Next</span></asp:LinkButton>

 

  • On the code behind aspx.cs page, you can generate all dynamic controls on Page_Init event

    protected void Page_Init(object sender, EventArgs e) { TextBox txt = new  TextBox(); txt.Text = QuestionText; txt.ID = "que1"; pnlQuestions.Controls.Add(txt); }

  • You can get all dynamic controls value on button click event like this

    protected void lbtnNext_Click(object sender, EventArgs e) { TextBox txt = ((TextBox)pnlQuestions.FindControl("que1")); AnswerText = txt.Text.Trim(); Response.Write(AnswerText); }

By using this method you can generate and fetch dynamic controls on asp.net page. I hope this will help you.

Tagged . Bookmark the permalink.

2 Responses to Run time dynamic controls in asp.net

  1. Sikander Ali says:

    Thanks Gaurav, this is very great in which you describe dynamic controls addition process in Asp.net page and it’s true most of developers or programmers doesn’t know how to add runtime controls and many use this process on page load event. and some are use static controls on page and use it in any another controls. But really this is the best way in all of them….

Leave a Reply