asp.net auto generated textboxes ID on webform - c#

I am using C# on Visual Studio. I want to generate a webform with auto numbered Textboxes depending on the input from the previous page. What is the best way to do this loop?
For example:
Input is 4
The next page should generate textboxes with ID of
"name1"
"name2"
"name3"
"name4"
Something like this :
<asp:TextBox ID="name1" runat="server"></asp:TextBox>
<asp:TextBox ID="name2" runat="server"></asp:TextBox>
<asp:TextBox ID="name3" runat="server"></asp:TextBox>
<asp:TextBox ID="name4" runat="server"></asp:TextBox>
Part 2 of my question is that if I want to call them when a Button is click, how should I use a loop the get those ID?

Use for loop and PlaceHolder control to create dynamic TextBox controls
<asp:PlaceHolder ID="phDynamicTextBox" runat="server" />
int inputFromPreviousPost = 4;
for(int i = 1; i <= inputFromPreviousPost; i++)
{
TextBox t = new TextBox();
t.ID = "name" + i.ToString();
}
//on button click retrieve controls inside placeholder control
protected void Button_Click(object sender, EventArgs e)
{
foreach(Control c in phDynamicTextBox.Controls)
{
try
{
TextBox t = (TextBox)c;
// gets textbox ID property
Response.Write(t.ID);
}
catch
{
}
}
}

You could create those controls in the Page Init event handler by say loop for the number of times the control needs to made available.
Please remember since these are dynamic controls they need to be recreated during postbacks and will not be done automatically.
Further Dynamic controls and postback

Check this code.
In first page...
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?Name=" + TextBox1.Text);
}
In second page you can get the value from querystring and create controls dynamically
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Name"] != null)
Response.Write(Request.QueryString["Name"]);
Int32 howmany = Int32.Parse(Request.QueryString["Name"]);
for (int i = 1; i < howmany + 1; i++)
{
TextBox tb = new TextBox();
tb.ID = "name" + i;
form1.Controls.Add(tb);
}
}

for ( int i=0; i<4; i++ )
{
TextBox t = new TextBox();
t.ID = "name" + i.ToString();
this.Controls.Add( t );
}

Related

connect asp repeaters with objects outside repeaters

I have a dropdown in my repeater.. i want to copy its value to textbox that is outside repeaters..
here is what I want to do
copy value from dropdown[1] to textbox1
copy value from dropdown[2] to textbox2 and so on...
here is my code
ASP:
<asp:DropDownList ID="fmFrom" runat="server" Height="20px" Width="120px" DataSourceID="BrDatasource" DataTextField="branchName" DataValueField="branchCode" AutoPostBack="true" onselectedindexchanged="fmFrom_SelectedIndexChanged"></asp:DropDownList>
c#:
protected void fmFrom_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < rateRepeater.Items.Count; i++)
{
DropDownList from = (DropDownList)rateRepeater.Items[i].FindControl("fmFrom");
TextBox1.Text = from.SelectedValue.ToString();
}
}
here all my textbox gets the value of the last dropdown only...
what should I do?
Try:
protected void fmFrom_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < rateRepeater.Items.Count; i++)
{
DropDownList from = (DropDownList)rateRepeater.Items[i].FindControl("fmFrom");
((TextBox)FindControl("TextBox" + (i + 1))).Text = from.SelectedValue.ToString();
}
}
change this:
TextBox1.Text = from.SelectedValue.ToString();
to:
TextBox1.Text += from.SelectedValue.ToString();

Visual 2012 C# ASP.net Add programmatically control under control

I'm designing in a web form.. the idea is like to design a forum -Like Here - where there is a main post body (Like this question im writing) and there be some replies to this question (like The ones will be answered to this question).
I have problem in putting reply comments under each other
I have made a reply button, when it is pressed,this code executes:
TextBox tb = new TextBox();
Panel3.Controls.Add(tb);
which panel3 is a panel under the main body, and textBox is a field for reply comments, and i want there to be as many as text boxes in the panel3 as the button is inserted.
when i click for the 2nd or 3rd or.... times, the current text box goes over the previous one and it wont go under it
how can i position each under previous text box?
This is related to CSS or HTML issues.
The idea is to add <div> to contain the TextBox before they are added to the panel.
Below are the sample codes:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Counter"] = 0;
}
else
{
//Sync ViewState Info to maintain the state
List<string> texts = new List<string>();
//The dynamic textbox values are captured from Request.Form
foreach (string key in Request.Form.Keys)
{
if (key.Contains("ctrlsuper"))
{
texts.Add(Request.Form[key]);
}
}
Texts = texts;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//Rerender the textboxes to UI and add one more new empty textbox.
for (int i = 0; i <= Convert.ToInt32(ViewState["Counter"]); i++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
TextBox tb = new TextBox();
tb.ID = "ctrlsuper" + i.ToString();
//Refresh the textbox text according to its previous value.
if (Texts.Count > 0 && i < Texts.Count)
{
tb.Text = Texts[i];
}
div.Controls.Add(tb);
pnlControls.Controls.Add(div);
}
ViewState["Counter"] = Convert.ToInt32(ViewState["Counter"]) + 1;
}
public List<string> Texts
{
get
{
if (ViewState["Texts"] == null)
{
return new List<string>();
}
else
{
return ViewState["Texts"] as List<string>;
}
}
set
{
ViewState["Texts"] = value;
}
}
}
The ASPX:
<asp:Panel runat="server" ID="pnlControls">
</asp:Panel>
<asp:Button runat="server" ID="btnAdd" Text="Add" OnClick="btnAdd_Click" />
Hope it helps.

Textbox disappears when linkbutton is clicked

I have a problem. I'm trying to make some panels, and in these panels I would like to have some linkbuttons, when the user click a linkbutton of a panel a textbox will appear in that panel, when I click in another linkbutton the textboxes of that panel also appear without problem but when I click in the other linkbutton the texboxes created in the previous panel disappears.
Here is my code:
public partial class _Default : Page
{
Label myLabel1;
Label myLabel2;
protected void Page_Load(object sender, EventArgs e)
{
myLabel1 = new Label();
myLabel2 = new Label();
Panel1.Controls.Add(myLabel1);
Panel2.Controls.Add(myLabel2);
if (!Page.IsPostBack)
{
//Remove the session when first time page loads.
Session.Remove("clicks");
Session.Remove("clicks2");
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
int rowCount = 0;
//initialize a session.
rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
//In each button clic save the numbers into the session.
Session["clicks"] = rowCount;
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount; i++)
{
TextBox TxtBoxU = new TextBox();
TxtBoxU.ID = "TextBoxU" + i.ToString();
//Add the labels and textboxes to the Panel.
Panel1.Controls.Add(TxtBoxU);
}
myLabel1.Text = rowCount + "";
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
int rowCount2 = 0;
//initialize a session.
rowCount2 = Convert.ToInt32(Session["clicks2"]);
rowCount2++;
//In each button clic save the numbers into the session.
Session["clicks2"] = rowCount2;
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount2; i++)
{
TextBox TxtBoxU = new TextBox();
TxtBoxU.ID = "TextBoxU" + i.ToString();
//Add the labels and textboxes to the Panel.
Panel2.Controls.Add(TxtBoxU);
}
myLabel2.Text = rowCount2 + "";
}
}
And here is the other part:
<form id="form1" runat="server">
<p>
Part I</p>
<asp:Panel ID="Panel1" runat="server" Height="53px">
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Add to 1</asp:LinkButton>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" Height="51px">
<asp:LinkButton ID="LinkButton2" runat="server" OnClick="LinkButton2_Click">Add to 2</asp:LinkButton>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</asp:Panel>
</form>
Since the text boxes are dynamically created, when the page loads everything needs to be re-built, but the code you posted only re-builds the text boxes for one of the panels when the particular link button for that panel is being clicked. However, your code is just building the one panel again, because that is all that your click event handlers for the link buttons are telling it to do.
I suggest combining the logic into a single method that does the building and then each link button click event handler can update its own count and pass it to the method, like this:
private void BuildTextBoxes(int rowCount1, int rowCount2)
{
for (int i = 0; i < rowCount; i++)
{
TextBox TxtBoxU = new TextBox();
TxtBoxU.ID = "TextBoxU" + i.ToString();
//Add the labels and textboxes to the Panel.
Panel1.Controls.Add(TxtBoxU);
}
myLabel1.Text = rowCount + "";
for (int i = 0; i < rowCount2; i++)
{
TextBox TxtBoxU = new TextBox();
TxtBoxU.ID = "TextBoxU" + i.ToString();
//Add the labels and textboxes to the Panel.
Panel2.Controls.Add(TxtBoxU);
}
myLabel2.Text = rowCount2 + "";
}
Now in your link button click event handlers, you will need to update the one count, but pass both to the method, like this:
protected void LinkButton1_Click(object sender, EventArgs e)
{
int rowCount = 0;
//initialize a session.
rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
//In each button clic save the numbers into the session.
Session["clicks"] = rowCount;
BuildTextBoxes(rowCount, Convert.ToInt32(Session["clicks2"]));
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
int rowCount2 = 0;
//initialize a session.
rowCount2 = Convert.ToInt32(Session["clicks2"]);
rowCount2++;
//In each button clic save the numbers into the session.
Session["clicks2"] = rowCount2;
BuildTextBoxes(Convert.ToInt32(Session["clicks1"]), rowCount2));
}
Now, whether you click the first or second link button, all of the text boxes will be recreated; with only the particular link button incrementing the number of rows.
When there is a post-back to the server following the click on the link an entirely new HTML page is generated and returned to the client. In the click event handler in your code you are adding additional controls to the ones in your aspx markup. These are then included in the HTML returned to the client. But the server is state-less and will not remember that you added these the next time there is a request from the client. You will need to add them again every time there is a post-back.
Maybe try to move your logic to add the text boxes into a separate method and then call it with the appropriate values in your click.
Something like this:
protected void LinkButton1_Click(object sender, EventArgs e)
{
int rowCount = Convert.ToInt32(Session["clicks"]) + 1;
Session["clicks"] = rowCount;
int rowCount2 = Convert.ToInt32(Session["clicks2"]) + 1;
Session["clicks2"] = rowCount2;
AddTextBoxes(rowCount, Panel1, myLabel1);
AddTextBoxes(rowCount2, Panel2, myLabel2);
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
int rowCount = Convert.ToInt32(Session["clicks"]) + 1;
Session["clicks"] = rowCount;
int rowCount2 = Convert.ToInt32(Session["clicks2"]) + 1;
Session["clicks2"] = rowCount2;
AddTextBoxes(rowCount, Panel1, myLabel1);
AddTextBoxes(rowCount2, Panel2, myLabel2);
}
protected void AddTextBoxes(int numberToAdd, Panel panel, Label label)
{
//In each button clic save the numbers into the session.
numberToAdd = rowCount;
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount; i++)
{
TextBox TxtBoxU = new TextBox();
TxtBoxU.ID = "TextBoxU" + i.ToString();
//Add the labels and textboxes to the Panel.
panel.Controls.Add(TxtBoxU);
}
label.Text = rowCount + "";
}

Get the value of Label in listview

I have a listview with invisible label to store the category Id.
what I want to do is to assign the text of the label to a cookie or session on button click.
the problem is my cookie is always null when I try to display the value outside the listview.
here is my aspx code:
<asp:ListView runat="server" ID="catListView" DataSourceID="CategoriesDataSource" >
<EmptyDataTemplate>No DataFound</EmptyDataTemplate>
<ItemTemplate>
<div class="service" style="margin-bottom:10px;width:230px;">
<h4 style="font-family:Corbel;" ><%#Eval("CatName") %></h4>
<asp:Label runat="server" Visible="false" ID="lblcat"><%#Eval("CatId") %></asp:Label>
<asp:Button runat="server" ID="btnTest" Text="View Items" OnClick="btnTest_Click" />
</div>
</ItemTemplate>
</asp:ListView>
my C# code:
protected void btnTest_Click(object sender, EventArgs e)
{
Response.Cookies["cat"].Value = "test";
foreach (ListViewItem item in catListView.Items)
{
Label catLabel = (Label)item.FindControl("lblcat");
Response.Cookies["cat"].Value = catLabel.Text.ToString();
}
}
any help will be appreciated.
thx in advance
Sam
It sounds like your ListView might not be databound when your Button click event is called.
I would recommend that you use the ItemCommand event handler. It is most appropriate for this type of handling. Update your ListView declaration to handle that event:
<asp:ListView runat="server" ID="catListView" DataSourceID="CategoriesDataSource
OnItemCommand="catListView_ItemCommand" >
Note: Don't forget to remove the "OnClick" event handler from the Button
And then write your even handler code like this:
protected void catListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Label catLabel = (Label)e.Item.FindControl("lblcat");
Session["currentCatLabelText"] = catLabel.Text;
}
This also has the advantage of not looping through all your ListView items, but just looking at the one you clicked.
Hope this helps :)
string[] catvals = new string[catListView.Items.Count];
for (int i =0; i< catListView.Items.Count; i++)
{
Label catLabel = (Label)catListView.FindControl("lblcat");
catvals[i] = catLabel.Text;
}
for(int i = 0 ; i < catvals.Length; i++)
{
Response.Cookies["cat"+ i.ToString()].Value = catvals[i].ToString();
}
Actually you are trying to add your cat in one key. I mean you are overwriting values in loop.
You should change your code in this way:
In your C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
HttpCookie testCokkie = new HttpCookie("ExampleCookie");
testCokkie.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(testCokkie);
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
HttpCookie ExampleCookie = Request.Cookies["ExampleCookie"];
int tempIndex = 0;
foreach (ListViewItem item in catListView.Items)
{
Label catLabel = (Label)item.FindControl("lblcat");
ExampleCookie["cat" + tempIndex.ToString()] = catLabel.Text.ToString();
tempIndex = tempIndex + 1;
}
}
TO read this cookie
HttpCookie exampleCookie = Request.Cookies["ExampleCookie"];
if (exampleCookie != null)
{
int tempIndex = 0;
foreach (ListViewItem item in catListView.Items)
{
Response.Write("<br/>" + exampleCookie["cat" + tempIndex.ToString()]);
tempIndex = tempIndex + 1;
}
}

Dynamically create textbox on button click

I have created a button whereby when it is clicked, it should display 3 textboxes in a row. However, every time i click the submit button, the textbox would display 2 rows(which is 6 textboxes). And subsequently increase 2 rows at every click.
Is there anyway that it could just increase one row of textbox at every click??
Here is the code infront:
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
</form>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
// Add any controls that have been previously added dynamically
for (int i = 0; i < TotalNumberAdded; i++)
{
AddControls(i + 1);
}
// Attach the event handler to the button
Button1.Click += new EventHandler(Button1_Click);
}
protected void Button1_Click(object sender, EventArgs e)
{
// Increase the number added and add the new label and textbox
TotalNumberAdded++;
AddControls(TotalNumberAdded);
}
private void AddControls(int controlNumber)
{
TextBox TxtBoxU = new TextBox();
TextBox TxtBoxE = new TextBox();
TextBox TxtBoxY = new TextBox();
Label lblU = new Label();
Label lblE = new Label();
Label lblY = new Label();
TxtBoxU.ID = "TextBoxU" + controlNumber;
TxtBoxE.ID = "TextBoxE" + controlNumber;
TxtBoxY.ID = "TextBoxY" + controlNumber;
lblU.ID = "LabelU" + controlNumber;
lblE.ID = "LabelE" + controlNumber;
lblY.ID = "LabelY" + +controlNumber;
lblU.Text = "User : ";
lblE.Text = "E-Mail : ";
lblY.Text = "Phone number : ";
//Add the labels and textboxes to the Panel.
Panel1.Controls.Add(lblU);
Panel1.Controls.Add(TxtBoxU);
Panel1.Controls.Add(TxtBoxU);
Panel1.Controls.Add(lblE);
Panel1.Controls.Add(TxtBoxE);
Panel1.Controls.Add(lblY);
Panel1.Controls.Add(TxtBoxY);
Panel1.Controls.Add(new LiteralControl("<br>"));
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
Your problem is in your page load, becouse your click event declaretion is redundant, you are attaching the EventHandler when you are assinging by HTML, And If you push click the event, It is fires 2 time.
Remove
Button1.Click += new EventHandler(Button1_Click);
And you page load will looks like:
protected void Page_Load(object sender, EventArgs e)
{
// Add any controls that have been previously added dynamically
for (int i = 0; i < TotalNumberAdded; i++)
{
AddControls(i + 1);
}
}
I hope that help.
P.S: I'm sorry in my first test I did not test right.
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txtobj = new TextBox();
Form.Controls.Add(txtobj);
txtobj.Text = "Dynamically Textbox";
}

Categories