Read textBox from dynamically created - c#

I am trying to create a textbox dynamically using a string. and then trying to read on a buttton click.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="textboxtest.aspx.cs" Inherits="test2.textboxtest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="TextBoxDiv" runat="server" class="asid box">
</div>
<asp:Button ID="Button1" runat="server" Text="CreateTextBox" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="ReadTextBox" onclick="Button2_Click" />
</asp:Content>
Here is the code behind.
protected void Button1_Click(object sender, EventArgs e)
{
string finalText = #"<input type=""text"" ID=""T1"" runat=""server"">
<asp:TextBox ID=""TB1"" runat=""server""></asp:TextBox>";
TextBoxDiv.InnerHtml = finalText;
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txtAddress2 = (TextBox)Page.FindControl("TB1");
foreach (Control c in TextBoxDiv.Controls)
{
if (c is TextBox)
{
TextBox txt = (TextBox)c;
string str = txt.Text;
}
}
}
As you can see from the code i have tried to access the textbox using find control and also looping through. but both are failing.

I managed to get it to work, but by only having to create dynamic textboxes in Page_Init event. So every time there is a post back you need to re-create your dynamic controls. You can check online, they say the same thing.
So here is the client side:
<asp:PlaceHolder runat="server" id="TextBoxesHere" />
<asp:Button ID="Button1" CssClass="btn btn-primary btn-outline" runat="server"
Text="CreateTextBox" OnClick="Button1_Click" />
<asp:Button ID="Button2" CssClass="btn btn-primary btn-outline" runat="server"
Text="ReadTextBox" OnClick="Button2_Click" />
Server Side:
protected void Page_Init(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "T1";
txt.CssClass = "form-control";
TextBoxesHere.Controls.Add(txt);
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "T1";
txt.CssClass = "form-control";
TextBoxesHere.Controls.Add(txt);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)TextBoxesHere.FindControl("T1");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('" + txt.Text + "');", true);
}

use a Placeholder instead of a div (it will generate a div) and then add controls in the placeholder instead of using InnerHtml.
So this can be achieved like this:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="textboxtest.aspx.cs" Inherits="test2.textboxtest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:PlaceHolder runat="server" ID="TextBoxPlaceHolder"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="CreateTextBox" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="ReadTextBox" onclick="Button2_Click" />
</asp:Content>
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
string finalText = #"<input type=""text"" ID=""T1"" runat=""server"">";
var textbox = new TextBox();
textbox.ID = "TB1";
this.TextBoxPlaceHolder.Controls.Add(new LiteralControl(finalText));
this.TextBoxPlaceHolder.Controls.Add(textbox);
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox txtAddress2 = (TextBox)Page.FindControl("TB1");
foreach (Control c in TextBoxDiv.Controls)
{
if (c is TextBox)
{
TextBox txt = (TextBox)c;
string str = txt.Text;
}
}
}

Related

Text property of a TextBox is empty when an async PostBack occurs

I've had a look at lots of posts and I feel like I'm going crazy as nothing I've tried seems to work. I simply want to click a button and retrieve the value of a textbox.
I'm using web forms with a site.master so not sure if this could be affecting the problem, but most of the solutions I've seen don't appear to be using a site.master.
I'm not binding the textbox, initially I just wanted to create a contact form.
<%# Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="Blackburn_Pulse.About" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>$("#menuAbout").addClass("navi-active");</script>
<div class="contentBody">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="tb_Test" EnableViewState="true" CausesValidation="false" runat="server"></asp:TextBox>
<asp:LinkButton ID="btn_Test" runat="server" OnClick="btn_Test_Click" Text="send test" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn_Test" EventName="click" />
</Triggers>
</asp:UpdatePanel>
</div>
</asp:Content>
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Master.EnableViewState = true;
if (IsPostBack)
{
var test_var = tb_Test.Text; //returning empty
}
}
protected void btn_Test_Click(object sender, EventArgs e)
{
var test_var = tb_Test.Text; //returning empty
}
}
UPDATE:
site.master.cs
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCategories();
}
}
protected void BindCategories()
{
Categories Categories = new Categories();
rpt_categories.DataSource = Categories.Get_Categories();
rpt_categories.DataBind();
}
protected void lb_newsCat_Command1(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "naviTo":
//Redirect user to selected category
Response.Redirect("~/" + e.CommandArgument.ToString());
break;
}
}
}
I'm converting a PHP website to an ASP.net website. Turns out I had another HTML form tag on a search box that I haven't started working on yet.
Unfortunately the debugger doesn't throw an error if you have another form tag so anybody else who's just spent hours of their lives searching, double check you don't have more than 1 form tag!
In my site.master.aspx file, I had a search box as follows:
<form method="post" action="?">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
</form>
Once I took the extra form tag out, everything worked fine.

Inject a textbox in WebForms and retain the value on postback

I have a WebForms page that I would like to inject some additional controls into at runtime. Currently I am achieving this in the Page_Load event using a Literal control.
For example the page looks like this (note that the TextBox1 is not an asp control just to show that it works):
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<input id="TextBox1" type="text" runat="server"/>
<asp:Literal ID="Literal1" runat="server" Visible="false"></asp:Literal>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Content>
And the code behind:
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Visible = true;
if (!IsPostBack) Literal1.Text = "<input id=\"TextBox2\" type=\"text\" runat=\"server\"/>";
}
This works fine and both textboxes appear on the screen but if I type a value in to both and trigger a postback only the value of TextBox1 is retained.
I have tried moving my code to OnPreRender and OnPreLoad but still have the same issue.
I have noticed that when I view the page source TextBox1 has a UniqueId (e.g. ctl00$MainContent$TextBox1) while Textbox2 still has runat="server" as an attribute.
You can't inject server controls like this. You would need to add them as suggested in #Arvin's answer.
However, you use inject non-ASP.NET HTML controls similar to what you are doing and get their values.
From your code change the input's id to a name and drop the runat="server":
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Visible = true;
if (!IsPostBack) Literal1.Text = "<input name=\"TextBox2\" type=\"text\" />";
}
Then you can get it's value on postback:
string textbox2value = Request.Form["TextBox2"];
Then, if you want to add the control on postback with it's value:
Literal1.Text = "<input name=\"TextBox2\" type=\"text\" value=\"" +
Server.HTMLEncode(textbox2value) + "\" />";
if you want to inject a textbox you should use placeholder like this :
<input id="TextBox1" type="text" runat="server"/>
<asp:PlaceHolder ID="plh" runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
protected void Page_Load(object sender, EventArgs e)
{
TextBox TextBox = new TextBox();
TextBox.ID = "TextBox2";
plh.Controls.Add(TextBox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var Text1 = TextBox1.Value;
var Text2 = Request.Form["TextBox2"];
}

DropDownList selected value lost on postback

On my page, i'm losing my dropdownlist's selected value on postback.
This is my aspx code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ProjectSearch.aspx.cs" Inherits="Site.Templates.ProjectSearch" MasterPageFile="~/Site/Templates/Framework/Base.master"
EnableViewState="true"%>
<asp:Content ID="Content1" ContentPlaceHolderID="Content" runat="server">
<div>
<ul>
<li class="filter">
<asp:DropDownList runat="server" ID="m_Filter" CssClass="form-control"/>
</li>
<li class="button">
<asp:LinkButton class="button-dark-orange" ID="m_search" runat="server" OnClick="m_search_click" >
Click
</asp:LinkButton>
</li>
</ul>
</div>
And in my code-behind there's nothing other than button click.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindDropdown();
}
}
public void BindDropdown()
{
try
{
List<int> ds = Filter.GetData()
m_filter.DataSource = ds;
m_Filter.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void m_search_click(object sender, EventArgs e)
{
Response.Write(m_Filter.SelectedIndex);
}
It always writes 0. Any help?
only add few things
<asp:DropDownList runat="server" ID="m_Filter" CssClass="form-control" AutoPostBack="true" />
write belove code in code behind file
ddlproduct.DataSource = your method;
ddlproduct.DataTextField = "text";
ddlproduct.DataValueField = "value";
ddlproduct.DataBind();

Unable to get textbox even when ID is defined

I am currently creating a page that a user will be able to input information and on submit it should save this information to a text file, however I seem to be unable to obtain the textbox as it appears to be undefined even when an ID is set on it, could someone please explain what I am doing wrong? As it seems to be working correctly with my btnSave method.
Backend C#:
public partial class Green_FreeShipping : System.Web.UI.Page
{
private static readonly string FILE_PATH = "~/TextFiles/Notes.txt";
private void GetNote()
{
using (TextReader tr = new StreamReader(MapPath(FILE_PATH)))
{
txtNote.Text = tr.ReadToEnd();
}
}
private void SaveNote()
{
using (TextWriter tw = new StreamWriter(MapPath(FILE_PATH)))
{
tw.Write(txtNote.Text);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetNote();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
this.SaveNote();
this.GetNote();
}
}
ASP.NET code:
<%# Page Language="C#" MasterPageFile="~/admin/masters/admin.master" autoeventwireup="true" inherits="TextBox_ReadWriteToTextFile" Title="Green & Free shipping amounts" codefile="~/admin/bespoke/Green-FreeShipping.aspx.cs"%>
<%# Register TagPrefix="web" Assembly="website.Web" Namespace="website.Web" %>
<%# Register TagPrefix="sales" Assembly="website.site.Web" Namespace="website.site.Web.Sales" %>
<%# Register TagPrefix="ecom" Namespace="website.site.Web" Assembly="website.site.Web" %>
<asp:Content ID="TitleContent" ContentPlaceHolderID="TitlePlaceHolder" runat="Server">
<title>Shopfront - Green and Free shipping amounts</title>
</asp:Content>
<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server">
<div style="margin-bottom: 20px;">
<asp:textbox id="txtNote" runat="server" rows="5" textmode="MultiLine" width="200px" />
</div>
<asp:button id="btnSave" runat="server" onclick="btnSave_Click" text="Save" />
</asp:content>
Your asp should inherit 'Green_FreeShipping' so that the c# can have access to the controls contained in it.

C# Dynamically filled DropDownList resets on button OnClick

I am having a bit of a DUH moment and need some help. I have a DropDownList control that gets filled with values on page load and a submit button that does further manipulations. However, when the button is clicked DropDownList returns a value of "-1" and not of the selected option. What is wrong here?
Web page:
<%# Page Language="C#" MasterPageFile="/new/MasterPageA2.master" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Checkout.aspx.cs" Inherits="Common_Checkout" EnableViewState="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="test11"></asp:Label>
<asp:DropDownList ID="ddlbillingcountry" required="true" EnableViewState="true" runat="server"></asp:DropDownList>
<asp:Button ID="ImageButton1" AlternateText="Proceed" OnClick="ImageButton1_Click" CausesValidation="false" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<p>Loading...</p>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Content>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
PopulateCountry(ddlbillingcountry);
}
}
private void PopulateCountry(DropDownList Controlname) {
DatasetTableAdapters.CountryTableAdapter _CountryTableAdapter = new DatasetTableAdapters.CountryTableAdapter();
Controlname.ClearSelection();
Controlname.Items.Clear();
DataTable _DataTable = _CountryTableAdapter._Eco_Country_Select();
Controlname.DataSource = _DataTable;
Controlname.DataTextField = "CountryName";
Controlname.DataValueField = "Country";
Controlname.DataBind();
Controlname.Items.Insert(0, new ListItem("- Select Country -", ""));
}
protected void ImageButton1_Click(object sender, EventArgs e) {
test11.Text += "<p>clicked " + ddlbillingcountry.SelectedIndex + " - " + ddlbillingcountry.SelectedValue.ToString();
}
You could set the datasource property to the name of a function which returns a dataset.
Try datasource='<%# PopulateCountry("ddlbillingcountry") %>' but you will need to change or overload the function to change the argument to a string, remembering to set the datavaluefield and datatextfield.Or you may want to create a separate function and call that with no arguments.

Categories