0

I have created a TextBox dynamically, and i am getting the value of the textbox when i click the button. But the value entered in the dynamic textbox gets empty when i click the button.

Below is my ASPX Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Reports.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>

<asp:DropDownList ID="DropDownList1" runat="server" 
    onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack = "true">
    <asp:ListItem>Text</asp:ListItem>
    <asp:ListItem>Check</asp:ListItem>
</asp:DropDownList> 

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="GetTextBoxValue" />   
</form>
</body>
</html>

CodeBehind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Reports
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox TB = new TextBox();
        TB.ID = "abc";
        form1.Controls.Add(TB);
        Response.Write(Request.Form["abc"]);
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        createcontrol();
    }


    protected void createcontrol()
    {
        if (DropDownList1.SelectedValue.ToLower().Trim() == "text")
        {
            TextBox TB = new TextBox();
            TB.ID = "abc";
            form1.Controls.Add(TB);
        }
    }
}
}

2 Answers 2

1

TextBoxes save their state by default. EnableViewState is true by default.

If you want to retain the text value, you have to add the TextBox on the Init or Load event.

Sign up to request clarification or add additional context in comments.

Comments

0

You should get you dynamically created controls, in Page_PreRender - event.

Like so: //get values

protected void Page_PreRender(object sender, EventArgs e) {
   //....
}

but you should use IsPostBack in Page_Load when you creating you element's.

this will help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.