Hello, I would like to assign text to a text box in a for next loop instead of the manual Textbox1.Text="Testing...";
I have a total of 10 text boxes and want to loop throught all of these ten text boxes and assign text depening on the results of the SQL query from user.. I am not in a level that I can dynamically create and dispo text box on-the-fly yet in VS 2005 aspx web page yet :). Right now I have an "if/ elseif" section to manually assign the text (textbox1.text="..";) depending how many items I get back from SQL results. I would like to learn how to create and dispo text boxes on the fly later on...
I cannot find anything from Googling.. yet. I tried the "TextBox tb = new TextBox();" and tried to assign an ID to it (e.g. tb.ID= String.Format("Textbox{0}.Visible", var1);" but I guess that this is only in memory. I found the property of all of my text boxes in "Controls[0]Textbox1.text" in the Controls but do not know to access it and assign text to it.
Appreciates tips and tricks from you.
Regards, HN
Hai NguyenPosted Mar 4, 2008, 1:00 PM
Hello Dilipv, Thank you for tips. This is great for create new text boxes for a web form.
What about assigning a new text for an existing text box (in Default.aspx)?
For example (See below): I already had a text box called "Textb_2". I tried the below but it added a new text box to my web page.
Appreciate for your help.
Regards, HN
______________
TextBox txb = new TextBox();
txb.ID = "Textb_2";
txb.Text = "Testing";
Page.Form.Controls.Add(txb);
dilipv vishwakarmaPosted Mar 4, 2008, 12:32 AM
First of all as you said web form have 10 textboxes then you need to create instances of 10 textboxes in Code behind page (ie aspx.cs) in for loop. You can assign unique ID and Text to 10 textboxes of web forms in same for loop. You can set text through data getting from database connection. After that you need to add all these control to Page. Form as follows.
protected
void Page_Load(object sender, EventArgs e){
for(int i=1;i<11;i++){
TextBox txt=new TextBox ();txt.ID=
"txt"+i;txt.Text =
"Text_From_Database";Page.Form .Controls .Add (txt);
}
}
Hope this will help you.
Thanks & Regards
Dilipv
Programmer
SharePoint Consulting