asp.net get the text from a dynamically inserted textbox return null all the time - asp.net

I am writing a web app in asp.net, in one of my aspx pages I have a static table.
To this table I insert a dynamically textbox control from the code behind (from Page_Load, I create this control dynamically because I do not know if I need to create it or not it depend on a user answer), the problem is when i try to get the textbox text after the user click on a button, I tried every thing i know from Request.Form.Get("id of the control") to Page.FindControl("id of the control"), but nothing works I get null all the time, just to be clear the button that activate the function that get the text from the textbox is insert dynamically to.
Both button and textbox are "sitting" in a table and must remain so, I'd appreciate any help
my code is:
aspx page
<asp:Table ID="TabelMessages" runat="server"></asp:Table>
code behind aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.ID = "textBox";
tb.Text = "hello world";
TableCell tc = new TableCell();
tc.Controls.Add(tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
}
public void Button_Click(object o, EventArgs e)
{
string a = Request.Form.Get("textBox");//does not work
Control aa = Page.FindControl("textBox");//does not work
}

in your
public void Button_Click(object o, EventArgs e)
{
//try searching in the TableMessage.Controls()
}

Alternatively, and depending on what you ultimately want to do, and still use Page_Load:
In your Page Class:
protected TextBox _tb; //this is what makes it work...
protected void Page_Load(object sender, EventArgs e)
{
_tb = new TextBox();
_tb.ID = "textBox";
TableCell tc = new TableCell();
tc.Controls.Add(_tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
if (!Page.IsPostBack)
{
_tb.Text = "hello world";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = _tb.Text; //this will display the text in the TextBox
}

You need to run your code inside the Page_PreInit method. This is where you need to add / re-add any dynamically created controls in order for them to function properly.
See more information about these types of issues in the MSDN article on the ASP.NET Page Life Cycle.

Try changing your Page_Load code to the following:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
TextBox tb = new TextBox();
tb.ID = "textBox";
tb.Text = "hello world";
TableCell tc = new TableCell();
tc.Controls.Add(tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
}

Related

Retrieving a Dynamically Generated TextBox Content in a GridView in ASP.NET

I have the following RowDataBound method for GridView2
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
List<TextBox> list = new List<TextBox>();
if (ViewState["Table"] != null)
Assessments = (DataTable)ViewState["Table"];
int count = 1;
foreach (DataRow row in Assessments.Rows)
{
TextBox txt = new TextBox();
txt.ID = "AsTxt";
txt.Text = string.Empty;
txt.TextChanged += OnTextChanged;
e.Row.Cells[count].Controls.Add(txt);
count += 2;
listd.Add((e.Row.DataItem as DataRowView).Row[0].ToString() + "Txt");
}
}
}
And the following event (Button Click) to retrieve whatever written in the text box in the GridView
protected void CalculateBtn_Click(object sender, EventArgs e)
{
GridViewRow rr = GridView2.Rows[0];
TextBox rrrr = (rr.FindControl("AsTxt") as TextBox);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rrrr.Text + "')", true);
}
I always get NullReferenceException. That mean the TextBox object (rrrr) is null always. I am sure that the text object sits in GridView2.Rows[0].
Why is this happening?
This is known issue with the Dynamical created controls in asp. So if you want to use the created control on your postback then I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.
Look at this blog this might help you
http://techbrij.com/retrieve-value-of-dynamic-controls-in-asp-net

The global variable doesn't keep its value

The problem is , every time i do a postback my variable "value" doesn't keep it's previous value, and always the dictionary is empty. It doesn't have any previous saved data. How can i make it to save data ?
this is the code :
public partial class MyCart : System.Web.UI.Page
{
public Dictionary<string, string> value = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
TextBox textbox = new TextBox();
textbox.TextChanged += textbox_TextChanged;
textbox.ID = "textbox" + p.IDProduct.ToString();
Button button = new Button();
}
void textbox_TextChanged(object sender, EventArgs e)
{
value.Add(((TextBox)sender).ID, ((TextBox)sender).Text);
}
}
The global variable are recreated on Postback you probably need to put the variable in ViewState for keep its data between postbacks.
If data is small the its fine with ViewState but if data is large then your might need to think an alternative medium of storage could be database.
To do it with ViewState you would need something like.
public Dictionary<string, string> value = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
if(ViewState["valDic"] != null)
value = (Dictionary<string, string>)ViewState["valDic"];
TextBox textbox = new TextBox();
textbox.TextChanged += textbox_TextChanged;
textbox.ID = "textbox" + p.IDProduct.ToString();
Button button = new Button();
}
void textbox_TextChanged(object sender, EventArgs e)
{
value.Add(((TextBox)sender).ID, ((TextBox)sender).Text);
ViewState["valDic"] = value;
}
View state is the method that the ASP.NET page framework uses to
preserve page and control values between round trips. When the HTML
markup for the page is rendered, the current state of the page and
values that must be retained during postback are serialized into
base64-encoded strings. This information is then put into the view
state hidden field or fields, MSDN.
After postbacks the variables lose the value as they are recreated..You can depend HTML hidden inputs..
Markup:
<input id="Hidden1" type="hidden" runat="server" value=""/>
Code behind:
Hidden1.value="something";

ASP.net : textChange Partial Update for programmatically inserted textboxes

I trying get some programmatically inserted textboxes (inserted into a gridview) to do a textChange partial update. It is sort of working but it does not automatically calls textEntered() method after I typed some text in these textboxes. I got a clue that I might need to use AJAX and things like updatepanels but I just don't fully understand how they will work in the context of what I am trying to do.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (!e.Row.Cells[4].Text.Equals(" ") && firstTime == false)
{
TextBox tb = new TextBox();
tb.Text = e.Row.Cells[4].Text;
tb.TextChanged += new EventHandler(textEntered);
textBoxArray.Add(tb);
int length = textBoxArray.Count - 1;
tb = (TextBox)textBoxArray[textBoxArray.Count - 1];
e.Row.Cells[4].Text = null;
e.Row.Cells[4].Controls.Add(tb);
Cache["textBoxArray"] = textBoxArray;
} firstTime = false;
}
protected void textEntered(object sender, EventArgs e)
{
lbl_test.Text += "test";//This line is for testing purposes
}
auto postback of textbox is true or false? make it true.

Accessing dynamically generated controls Object reference not set to an instance of an object

I am adding controls dynamically to my page on the basis on a condition.There's a button in these controls, to which i have attached an event handler as well for click event.Now in this event handler, i am trying to access my dynamically generated controls, but getting an exception. Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
String Method = Request.QueryString["Method"];
String Tag = Request.QueryString["Tag"];
if (Method=="ADD" && Tag=="METHOD")
{
//6
TableCell cell11 = new TableCell();
cell11.Text = "NEXTLEVEL";
TableCell cell12 = new TableCell();
TextBox txt6 = new TextBox();
txt6.ID = "txt6";
cell12.Controls.Add(txt6);
TableRow row6 = new TableRow();
row6.Cells.Add(cell11);
row6.Cells.Add(cell12);
container.Rows.Add(row6);
TableCell cell14 = new TableCell();
Button submit = new Button();
submit.ID = "SubmitButton";
submit.Text = "Submit";
submit.Click += new EventHandler(submit_Click);
cell14.Controls.Add(submit);
TableRow row7 = new TableRow();
row7.Cells.Add(cell14);
container.Rows.Add(row7);
}
void submit_Click(object sender, EventArgs e)
{
ModifySessionAnalyzer msa = new ModifySessionAnalyzer();
TextBox txt6= (TextBox)Page.FindControl("txt6") as TextBox;
##String message = txt6.Text;##
}
TableCell cell12 = new TableCell();
TextBox txt6 = new TextBox();
txt6.ID = "txt6";
cell12.Controls.Add(new TextBox());
This is wrong, you are not adding the txt6 control to the cell, instead you are adding a new textBox...
Dynamically added controls should be added in the Page_Init method not Page_Load. If they are added into Page_Load they won't be added to the control tree and you'll get issues - i.e. they won't participate in ViewState correctly.
So (TextBox)Page.FindControl("txt6") could fail as the text box is no longer in the control tree
This could be the source of your issue.
Further explanation
Your code should be
protected void Page_Init(object sender, EventArgs e)
{
//.. your code goes here
}
NOT
protected void Page_Load(object sender, EventArgs e)
{
//.. your code
}
It's normal practice to use Page_Load so it's just an easy habit for people but when using dynamic controls then this is the exception
When i say dynamic controls - it's anything when you are added controls on the fly rather than declaring them in your page. Look for anything where you are going Controls.Add

Declaring a CLICK event. ASPX vs Code behind.. how are these 2 different?

in .ASPX this is working
<asp:ImageButton ID="lbHope6" runat="server" ImageUrl="~/Shared/Images/Site/ChartTypeProd.png"
CssClass="chart" OnClick="lbHope6_Click" />
protected void lbHope6_Click(object sender, ImageClickEventArgs e)
{
EventArgs args = new EventArgs();
if (Hope6 != null)
Hope6(this, args);
}
but when I do it this way it acts differently.. any ideas?? ive given up hope
LinkButton lb = new LinkButton();
lb.Text = s.Key.ToString();
lb.Click += new EventHandler(lbHope6_Click);
sourceNameCell.Controls.Add(lb);
protected void lbHope6_Click(object sender, EventArgs e)
{
EventArgs args = new EventArgs();
if (Hope6 != null)
Hope6(this, args);
}
You're creating the new link button and assigning an eventhandler every time the page loads (including on postback). .Net won't understand that the LinkButton you create on postback is in fact the LinkButton you created when the page was first called. Your first code sample was fine.

Resources