Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to get the value of dynamically created textbox in another button event?

Posted on 2011-10-20
17
Medium Priority
?
2,563 Views
Last Modified: 2012-05-12
Hi, In below code I am generating dynamic text box in gridview at run time and showing text box in aspx page, below is the code:
protected void dropdownlist_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView2.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    for (int z = 0; z < 3; z++)
                    {
                        TextBox tb = new TextBox();
                        tb.ID = "txtbox_" + z.ToString();  //text box id
                        row.Cells[z].Controls.Add(tb);
                    }
                }
            }
}
//------------------------------------------------------------------------------------
Now, I am entering some values in text boxes which are dynamically created and want to get these values and display in label when click button, below is the code for button:
protected void button_Click(object sender, EventArgs e)
{
  Label1.Text = ((TextBox)GridView2.Rows[0].Cells[0].FindControl("txtbox_0")).Text;
  Label2.Text = ((TextBox)GridView2.Rows[0].Cells[1].FindControl("txtbox_1")).Text;
  Label3.Text = ((TextBox)GridView2.Rows[0].Cells[2].FindControl("txtbox_2")).Text;
}
//----------------------------------------------------------------------------------------
But I am getting below error:
Object reference not set to an instance of an object.   at AdminPolicy.BatchCheckIn.button_Click(Object sender, EventArgs e) in C:\AdminPolicy\AdminPolicy\BatchCheckIn.aspx.cs:line 286
   at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
//------------------------------------------

Kindly help me
0
Comment
Question by:Minesh Shah
  • 7
  • 6
  • 2
  • +2
17 Comments
 
LVL 23

Expert Comment

by:Rajkumar Gs
ID: 36998170
0
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 36998207
try like this

Label1.Text  = ((Label) GridView2.Rows[0].FindControl("txtbox_0")).Text
0
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 36998214
One mistake in above line
Label1.Text  = ((TextBox) GridView2.Rows[0].FindControl("txtbox_0")).Text
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 10

Author Comment

by:Minesh Shah
ID: 36998615
Dear Sonawanekiran, above line is not working giving same error.

Dear RajkumarGS, i don't want to change the code as per given link, now so please guide and give some more idea.
0
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 36999236
The problem is that you're expecting the control to be somplace it might not actually be. It's in there, but you need to figure out which controlset it actually belongs to. Given the exceptions you're getting, I'm guessing it's somewhere closer to GridView2.Rows[0].Cells[0].Controls[0]...

The simplest and quickest way to get around your problem is going to be to set a breakpoint at line 286 and check through the controls for Cells 0 through 2 of the GridView.Row to determine where your dynamically added TextBox actually lives.
0
 
LVL 7

Expert Comment

by:kovilpattiBalu
ID: 36999464
hi,

In "dropdownlist_SelectedIndexChanged" store the values in Hashtable, and in "button_Click" get the values from Hashtable and display in label. Declare hashtable as page level.
0
 
LVL 10

Author Comment

by:Minesh Shah
ID: 37005332
Dear azarc3,
If I write below code inside “dropdownlist_ SelectedIndexChanged” then it’s working but if inside “button_Click” then showing error:
Label1.Text = ((TextBox)gridviewtemp.Rows[0].Cells[0].FindControl("txtbox_0")).Text;
Label2.Text = ((TextBox)gridviewtemp.Rows[0].Cells[1].FindControl("txtbox_1")).Text;
Label3.Text = ((TextBox)gridviewtemp.Rows[0].Cells[2].FindControl("txtbox_2")).Text;
}
//---------------------------
Dear kovilpattiBalu,
I tried to use Hash Table but no luck still same error, below is the code:
namespace AdminPolicy
{
public partial class BatchCheckIn : System.Web.UI.Page
{
        Hashtable hshTable;
protected void ddlFolder_SelectedIndexChanged(object sender, EventArgs e)
       {
       foreach (GridViewRow row in GridView2.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    for (int z = 0; z < 3; z++)
                    {
                        TextBox tb = new TextBox();
                        tb.ID = "txtbox_" + z.ToString();  //text box id
                        row.Cells[z].Controls.Add(tb);
                    }
                }
            }
         hshTable.Add("CurrentTable", GridView2);
       }
protected void btnCheckin_Click(object sender, EventArgs e)
        {
            GridView gridviewtemp = (GridView)hshTable["CurrentTable"];
            Label1.Text = ((TextBox)gridviewtemp.Rows[0].Cells[0].FindControl("txtbox_0")).Text;
            Label2.Text = ((TextBox)gridviewtemp.Rows[0].Cells[1].FindControl("txtbox_1")).Text;
            Label3.Text = ((TextBox)gridviewtemp.Rows[0].Cells[2].FindControl("txtbox_2")).Text;
        }
    }
}
//-------------------------------------
Please please help me I am finding solution from last 10 days but nothing happened.
Regards,
0
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 37005748
Do the controls exist when the button is clicked? I don't mean visible on the page... I mean in the stack for page processing. Have you tried setting a break point in the Click event and debugging that to see if the controls are "there" WHEN you expect them to be? Because they're being added dynamically they may not be. Debugging and stepping through the control set(s) for the GridView.Row[0].Cells[n] will answer this question.

If you find that the controls aren't there WHEN you expect them to be then I recommend getting the values from Request.Form instead.
0
 
LVL 10

Author Comment

by:Minesh Shah
ID: 37092981
Can you please give me some example code how to use Request.Form to get text box control from GridView
0
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 37093555
That's just it... it's not going to be associated, per se, with the GridView. Rather, it's going to be part of whatever is sent as the postback to the server.

Here's how to iterate over all the keys in the Request.Form submission...
------------------------------------------------------------------------------------
foreach (var key in Request.Form.AllKeys)
{
      if (Request.Form[key] == ControlName.ClientID)
      {
            // do what you want here
      }
}
------------------------------------------------------------------------------------


Obviously, this is the more inefficient way of going about this. To access a specific key directly...
------------------------------------------------------------------------------------
if (Request.Form.AllKeys.Contains(ControlName.ClientID))
{
      string value = Request.Form[ControlName.ClientID];
      // do what you want with value here
}
------------------------------------------------------------------------------------


In both of these examples, you can simply supply the actual field name (in the HTML) rather than using ControlName.ClientID... in fact, in your case that will probably be the best thing to do since you won't have design time IntelliSense support for controls added at runtime.


Given the scenario, here's how I would do it if I "knew" what the field names were going to be when the form is submitted...
------------------------------------------------------------------------------------
string[] myFields = new string[] { "fieldName0", "fieldName1", "fieldName2", "fieldName3", "fieldName4", "fieldName5", "fieldName6", };

foreach (var key in myFields)
{
      if (Request.Form.AllKeys.Contains(key))
      {
            string value = Request.Form[key];
            // do what you want with value here
      }
}
------------------------------------------------------------------------------------


One little pitfall that has tripped me up before is that you'll only have a value for ControlName.ClientID if it's a postback OR if the user arrived at this page because of a form submission. If not, then the key won't exist in the Request.Form collection.

-Happy Coding!
0
 
LVL 10

Author Comment

by:Minesh Shah
ID: 37181252
Sorry, it's not working. same erroe is coming.
0
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 37182998
It sounds to me like your button_click is firing before the page is aware of your values.

This is important, because only you can debug the page and let us know what's happening: Are there 4 or more than keys in Request.Form.Keys when you debug the page and you click the button? You'll find this out when you set a break point inside that button_click event.

If you've only got the standard three keys (such as "_VIEWSTATE"; I don't recall the other two), or less, then that means the data you're looking for doesn't "exist" yet. If that's the case, try moving your code into the Page_Load event. You'll get an error if you don't check for if(IsPostback).
0
 
LVL 10

Author Comment

by:Minesh Shah
ID: 37254125
No, after creation of textboxes dynamically, i enterd value and then clicking button event.
0
 
LVL 11

Expert Comment

by:Kelvin McDaniel
ID: 37255577
That's not what I mean. You should look up the ASP.NET Page Lifecycle and you'll get an idea of what I'm talking about.

The first paragraph on that page reads:
When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend.

Again, please try moving the code that evaluates the control you're trying to access to the Page_Load event.
0
 
LVL 10

Author Comment

by:Minesh Shah
ID: 37301557
Hi, below I am giving sample code for dynamically generated text box, please copy and paste it in to your visual studio and run and then please resolve the issue:

-------------------------------------------ASPX Page (Test.aspx)-----------------------------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Generate Text Box" /><br />
        <br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Get Values" /><br />
        &nbsp;
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
        &nbsp;
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
        &nbsp;
        <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

----------------------------------------------Code file (Test.aspx.cs)-------------------------------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Test : System.Web.UI.Page
{
    TextBox tb;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable fieldTable = new DataTable();
        DataRow frow;
        DataColumn fcolumn;
        fcolumn = new DataColumn("Name");
        fieldTable.Columns.Add(fcolumn);
        fcolumn = new DataColumn("Title");
        fieldTable.Columns.Add(fcolumn);
        fcolumn = new DataColumn("Location");
        fieldTable.Columns.Add(fcolumn);
        frow = fieldTable.NewRow();
        for (int j = 0; j < 3; j++)
        {
            frow[j] = "";
        }
        fieldTable.Rows.Add(frow);
        GridView1.DataSource = fieldTable;
        GridView1.DataBind();
        CreateDynamicControls();
    }
    public void CreateDynamicControls()
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                for (int z = 0; z < 3; z++)
                {
                    tb = new TextBox();
                    tb.ID = "txtbox_" + z.ToString();
                    row.Cells[z].Controls.Add(tb);
                }
            }
        }
 
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        //How to get value from text box and show in labels.
        //Label1.Text = ((TextBox)GridView1.Rows[0].FindControl("txtbox_0")).Text; //not working
        Label2.Text = ((TextBox)GridView1.Rows[0].Cells[1].FindControl("GridView1_ctl02_txtbox_1")).Text; //not working
        Label3.Text = ((TextBox)GridView1.Rows[0].Cells[2].FindControl("txtbox_2")).Text; //not working
    }
}
----------------------------------------------------------------------------------

waiting for reply.
0
 
LVL 11

Accepted Solution

by:
Kelvin McDaniel earned 2000 total points
ID: 37309048
As I alluded to in my second comment, the only way you're going to get the values of these dynamically added textboxes (without a LOT more unnecessary code and work) is to use Request.Form. Using the code you provided, here's the output of Request.Form when I loop through the keys:

KEY 0: __VIEWSTATE
VALUE: /wEPDwUJNTMxMzM1MzY2D2QWAmYPZBYCAgMPZBYCAgUPZBYCAgMPPCsAEQIADxYEHgtfIURhdGFCb3VuZGceC18hSXRlbUNvdW50AgFkDBQrAAMWCB4ETmFtZQUETmFtZR4KSXNSZWFkT
25seWgeBFR5cGUZKwIeCURhdGFGaWVsZAUETmFtZRYIHwIFBVRpdGxlHwNoHwQZKwIfBQUFVGl0bGUWCB8CBQhMb2NhdGlvbh8DaB8EGSsCHwUFCExvY2F0aW9uFgJmD2QWBAIBD2QWBmYPDxY
CHgRUZXh0BQYmbmJzcDtkZAIBDw8WAh8GBQYmbmJzcDtkZAICDw8WAh8GBQYmbmJzcDtkZAICDw8WAh4HVmlzaWJsZWhkZBgBBRtjdGwwMCRNYWluQ29udGVudCRHcmlkVmlldzEPPCsADAEIAgF
k1JoxuBrXQT64QGgMRN0z5zF1BMZIRnkuvx/cJ7eXGns= // <-- I added carriage returns to this VALUE to make sure it would wrap on screen.

KEY 1: __EVENTVALIDATION
VALUE: /wEWBgKq9/SzCwLT8MqYCAKOtKqfCwKOtK6fCwKOtLKfCwLU8MqYCC0Jb9raXAPTnKysmYgyYSbtZWrFGCeASqotVGL7GA+R

KEY 2: ctl00$MainContent$GridView1$ctl02$txtbox_0
VALUE: Left    // <-- I typed this in the generated form field before clicking the "Get Values" button.

KEY 3: ctl00$MainContent$GridView1$ctl02$txtbox_1
VALUE: Center    // <-- I typed this in the generated form field before clicking the "Get Values" button.

KEY 4: ctl00$MainContent$GridView1$ctl02$txtbox_2
VALUE: Right    // <-- I typed this in the generated form field before clicking the "Get Values" button.

KEY 5: ctl00$MainContent$Button2
VALUE: Get Values

Below is the code I used to get the values; everything else can remain the same (though in my working sample I simplified it quite a bit):

protected void Button2_Click(object sender, EventArgs e)
{
	//How to get value from text box and show in labels.

	Label1.Text = Request.Form[2];
	// Label1.Text = Request.Form["ctl00$MainContent$GridView1$ctl02$txtbox_0"]; // <-- this will also work.
	
	Label2.Text = Request.Form[3];
	// Label2.Text = Request.Form["ctl00$MainContent$GridView1$ctl02$txtbox_1"]; // <-- this will also work.

	Label3.Text = Request.Form[4];
	// Label3.Text = Request.Form["ctl00$MainContent$GridView1$ctl02$txtbox_2"]; // <-- this will also work.
	
	var sb = new System.Text.StringBuilder();

	foreach (var key in Request.Form.Keys)
	{
		sb.AppendFormat("<p>{0}:<br />{1}</p>", key, Request.Form[key.ToString()]);
	}

	Label4.Text = sb.ToString();
}

Open in new window

0
 
LVL 10

Author Closing Comment

by:Minesh Shah
ID: 37313689
Dear azarc3, that is called perfect answer now it's working.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question