How do I add a textbox dynamically in ASP.NET? - asp.net

I've a following requirement for my asp.net page:
User can add a textbox dynamically on a page A by clicking on link "Add a new category" hyperlink
He clicks submit button on page A and gets redirected to page B.
When he clicks on page A link from this page, the textboxes that he added should be persisted.
Can someone help me with the code on this?
Appreciate your help!

In the ButtonClick Method write.
TextBox tb = new TextBox();
Parent.Controls.Add( tb );
The Parent is the control you want to add the textbox to, for instance a panel.
You can also look at this resource.
Hope it helps.

Adding a user control dynamically is simple. But in this case, I don't think you need to do that, instead you should look at creating a repeater with a textbox inside it, and when the user clicks Add Category, add one item to the repeater datasource.
This way you can handle both control creation and state persistence at the same time.

dealing with dynamic user controls can be a pain in the ass.
as a rule of thumb i follow, whenever you create a dynamic user control, then you must set it's ID so ASP.net can reallocate it on post back, and to keep the controls values after post back you should reload your user controls on Page_Init event.
hope this helps.

Dynamically creating Textboxes:
suppose you have page like this
when you enter '1' in textbox and click on ADD button,output will be like display one textbox
below..
i have designed like this,
i have one textbox and placeholder for displaying dynamic textboxes..
double click on Add button...in btnadd_click,you have to write the following code
protected void btnadd_Click(object sender, EventArgs e)
{
int i;
for (i = 0; i < Convert.ToInt32(txtno.Text); i++)
{
TextBox txtbox = new TextBox();
phtxt.Controls.Add(txtbox);
phtxt.Controls.Add(new LiteralControl("<br>"));
}
}
debug it... and the output is,

As others have stated adding the text box dynamically is fairly straight forward, just create the Textbox and add it to the controls collections wherever you need it to show up. You then need to store the information that this user gets this additional text box. Assuming that this is meant for long term, you will need to store this information in your backend store. Whenever you are constructing the page you will need to read the store information first to see what textboxes to create.
I would suggest doing it as follows. In the Onload event, if you have not done so before, load the dynamic information from your DB. Add any necessary controls to the page and store this information in viewstate. On any subsequent postbacks, read the information from viewstate to add the additional controls. This will save you from having to read constantly from the database on each postback.

Related

ASP .Net Textbox Textchanged event

I have a webpage. I show records from table, lets say, students in my page. I query all the students and show them in grid. I want to use a textbox for filtering the datagridview results. For example if the user types a in the textbox the grid will show only the students who has "a" in his/her name. I want to refresh the grid at the same time while textbox is being edited.
i have set the autopostback property of textbox to true, and i refresh the grid in textbox's textchanged event.But the textchanged event fires only after the textbox loses focus. How can I make it fire after user types just one character ? thanks.
You have to use the onKeyDown event. However, I'd advise you to use ASP.NET AJAX or jQuery to load the results with Ajax.
Here is one example from asp.net: http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/AutoComplete/AutoComplete.aspx
Another one, from Code project:
http://www.codeproject.com/Articles/38803/Google-Like-Search-TextBox
You might want to show some your present code, if there is a particular method you want to go with for this. Otherwise your going to get a people telling you the way they would do it.
Does it look something like this right now?
<asp:Textbox id="myTextbox" runat="server" onChange="txtChanged" AutoPostBack="true"/>
public void txtChanged(object sender, EventArgs e)
{
//Get text from textbox
string text = ((TextBox)sender).Text;
//Do what ever it is you want to do to edit the text
text = text.ToUpper();
//Update the other textbox with this text
txtMyText2.Text = text;
}
I think the best and most clean way is to use Rad Controls, here is an example on how to do it:
http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandcombo/defaultcs.aspx?product=grid
The event TextChanged only fires when you send a request to server. If you wanna launch an event or make a function when the text inside textbox changes, use an OnKeyDown event (right with Schiavini).
You can use PicNet to do this in the Client instead of the Server for a better User experience. You can find it here http://www.picnet.com.au/resources/tablefilter/demo.htm Remember that the Gridview is rendered as a HTML table, therefore you can freely use this jQuery plugin.
Good luck!

How can I handle a button event that triggers user control creation?

I have an ASP.NET web form on which I'm displaying a list of database items via user controls, generating the user controls dynamically - working fine.
Also on the page, I have an asp:dropdownlist filled with items that can be added to this database list. Along with this dropdown I have a button 'ADD'. My intent is that the user chooses and item, clicks add, and then the list of user controls on the form will include this new item.
I have all this working.
My issue is that the user control has a button 'DELETE', which removes the selected item from the list. That works, EXCEPT when I add a new item. Because my 'add' button event is always fired after Page_Load, even if I regenerate the list of user controls, the internal user control click events won't fire because the controls weren't created as part of Page_Load.
I need to know what I'm doing wrong, or best practices here, any advice. I tried to be precise in the description of the problem, but if I've not succeeded, let me know and I can add more details.
SIMPLE RESTATE: I need to know how to add a dynamically created user control to a page via a page button click event, and still have the user control internal click(etc) events firing.
Thanks for any help.
EDIT: Based on the feedback from the gentlemen here, and doing some further research related to their suggestions, I ended up implementing a solution based on what's presented on this page:
http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx
Here's a snippet showing how I dealt with this. This snippet resides in my PreInit event handler. Not exactly an elegant weapon for a civilized age, but sometimes a blaster is all you've got to use.
'Look to see if button for adding a new client number has been
'clicked. If so, call the sub to add the item NOW, so that it
'is able to have it's internal click events fire.
For Each control_string As String In Request.Form
Dim ctl As Control = Page.FindControl(control_string)
If (ctl IsNot Nothing) AndAlso (ctl.ID = "cmdAddClientNumber") Then
Me.AddClientNumberToList()
Exit For
End If
Next
On the button handler, you initially add the UserControl to the Page. OnPreInit (which will next be fired when the user clicks Delete on the UserControl), you should re-add the UserControl - so that it exists, and can handle the Delete button event.
You will need to devise your own state tracking mechanism to determine that you need to add the UserControl during PreInit. I generally use ViewState, as evidenced by this seemingly similar post.
Similar question:
How to create and use custom control with UpdatePanel added to the page programmatically
Dynamic control should be re-added to the control tree OnPreInit, see documentation:
PreInit - Create or re-create dynamic controls.
ASP.NET Page Life Cycle Overview

ASP.NET User Controls - Problem adding multiple instances programmatically?

I have created a user control which basically consists of 3 text boxes. I want to allow the user to click a hyperlink which will add a new instance of the user control onto a PlaceHolder. This seems to be working as I populate one of the text box controls with a random number which changes whenever I click the hyperlink. However, it is overwriting the previous control.
Heres the code on MyPage.aspx
protected void MyHyperlink_Click(object sender, EventArgs e)
{
var uc = new MyUserControl();
uc = (MyUserControl)LoadControl("~/path/to/my/usercontrol.ascx");
placeHolderCtrl.Controls.Add(uc);
}
Basically what I need to know is how can I get the control adding different instances underneath eachother as it just seems to be 1 control being overwritten each time.
Thanks.
The problem is after the postback, your previously added controls are not added to the placeholder. Dynamically added control should be added on each postback. My recommendation is to store a counter in a variable and at your page load, add your web controls again depending to this counter.

Adding a textbox dynamically

In my aspx page,when a user clicks on a Location "LinkButton", a new textbox should be dynamically added in the page.User can add a maximum of 10 textboxes.
Also, user can navigate to another page B from this page A.When he comes back to page A, all his textboxes should be persisted.
How do I achieve this functionality?
Thanks.
I would create a user control with a place holder object in it and then write something like:
if(NumberOfTextBoxes <= 10)
{
TextBox tb = new TextBox();
Placeholder1.Controls.Add(tb);
NumberOfTextBoxes++;
}
For reference I would recommend:
How to: Add Controls to an ASP.NET
Web Page Programmatically
PlaceHolder Class (The remarks section has a lot of HowTo's like the one above)
You need to keep information in the user's session about how many text boxes to show (and possibly their content). In the page's Init (?) handler you will need to add the text boxes each time.

Creating custom server control to accept user input

I am trying to build a server control that, depending on a "QuestionTypeId" display either a text box, date picker or Yes-No radio buttons.
I have my control displaying how I want it to, but when the submit button is pressed on the form, the text box, date picker or radio buttons that were generated in the RenderContents method are all null.
I have attempted to store the generated controls in view state, that stopped them being null, but the user inputs were not being stored.
I will post code if it is needed. Just ask.
I think you need to create (and add) the controls in CreateChildControls. This will mean you'll need to store the value of the QuestionTypeId in either Viewstate or ControlState (I'd argue that ControlState is applicable in this case, as your control can't work without this value).
When you add controls dynamically, you need to make sure they are recreated before the viewstate is restored.
I haven't done this in a while, but from memory I think you should recreate your controls in the OnInit method. This happens before postback data has been loaded and before the controls have their values set from viewstate.
It may be worth doing some reading on the asp.net page lifecycle:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
You can create a user control and use server controls for textbox, datepicker, radiobuttons.
If you create a cusom server control then you have to add the posted data to your control properties. You can do this at your control OnInit event:
MyProperty = Request.Form("myControl");
A simpler method would be to create all the controls at design time and make the controls invisible based on you requirements.
Example code:
protected void Page_Load(object sender, EventArgs e)
{
txtBox.Visible = QuestionTypeID == 1;
chkBox.Visible = QuestionTypeID == 2;
}
If you do use dynamic controls you should do as David pointed out, save the value QuestionTypeID in ViewState or ControlState and then create the control you want based on that value.
(the control needs to be created every time the page loads even on a post back and they cannot be created later in the page life cycle then the Page_Load method if you want their ViewState persisted and recovered)
Example code:
protected void Page_Load(object sender, EventArgs e)
{
var questionId = ViewState["QuestionTypeID"];
if(questionId == /* Value to create TextBox */) {
var txt = new TextBox { ID = "txt" };
placeHolder.Controls.Add(txt);
} else if(questionId == /* Value to create Calender */) {
var cal = new Calender { ID = "cal" };
placeHolder.Controls.Add(cal);
}
/* Once the controls are added they will be populated with the posted values */
}
P.S.
It's always a good idea with dynamic controls to specify the ID.
You can save the added controls to member variables and use them elsewhere (after they are assigned)
You can subscribe to their events and if the user posted a new value your method will be called
I have followed your advice and done the following:
1) Question Type is stored in view state in my server control.
2) on CreateChildControls now creates a new instance of my control and adds it to a place holder on the page.
My problem now is that things seem to fire in bit of an odd order:
1)On initial load of page, create child controls is fired and the RenderContents method of my server control fires.
2)A button is clicked to load a new contact, this triggers create child controls and RenderContents is fired.
3)details are entered and save is pressed, this triggers Create Child Controls but RenderContents is not triggered and a NullReferenceException is generated by trying to access my control to get the value out. (If i skip the code that access my controls, RenderContents is called and renders.
Seconly, another issue is that when I try an set a value (onDataBind) I try to access the Text box that has been generated in my server control and get another NullReferanceExeption
Thoughts?

Resources