basuraj kumbhar
basuraj kumbhar

Reputation: 104

How to get dynamically created textbox value

I want to get dynamically created textbox value in asp.net

This is code which I have created in this code text box are created but when I will input the value in the text and retrieve the value from dynamically created text box it give error

Object reference not set to an instance of an object

Below is my code...

protected void Page_Init(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //Generate initial textboxes 
        GenerateButton_Click(sender, e);
    }
}
protected void GenerateButton_Click(object sender, EventArgs e)
{
    //Generate textboxes 
    int z = int.Parse(HowManyToGenerateTextBox.Text);

    Panel1.Controls.Clear();

    for (int i = 0; i < z; i++)
    {
        TextBox s = new TextBox();
        s.ID = "tb" + i.ToString();
        Session[s.ID] = s;
        Panel1.Controls.Add(s);
    }
}
protected void CalculateButton_Click(object sender, EventArgs e)
{
    //Calculate sum 
    int sum = 0;

    for (int i = 0; i < Session.Count; i++)
    {
        TextBox txt = (TextBox)Panel1.FindControl("tb" + i.ToString());
        ResultLabel.Text = txt.Text;


        if (ResultLabel.Text != null)
            sum += int.Parse(ResultLabel.Text);
    }

    ResultLabel.Text = sum.ToString();
}

Upvotes: 1

Views: 1000

Answers (2)

basuraj kumbhar
basuraj kumbhar

Reputation: 104

Hello Friend Here is answer

 protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
        GenerateButton_Click(sender, e);
}


public TextBox[] s;

protected void GenerateButton_Click(object sender, EventArgs e)
{

  int z = Convert.ToInt32(HowManyToGenerateTextBox.Text);
  Panel1.Controls.Clear();
  Array.Resize(ref s, z);
  for (int i = 0; i < z; i++)
  {
      s[i] = new TextBox();
      s[i].ID = "tb" + i.ToString();
      s[i].Text = "tb" + i.ToString();
      Session[s[i].ID] = s;
      Panel1.Controls.Add(s[i]);
  }
}
protected void CalculateButton_Click(object sender, EventArgs e)
{
   ResultLabel.Text = s[0].Text;      
}

Here is also code http://www.codeproject.com/Questions/854773/How-to-get-dynamically-created-textbox-value

Upvotes: 0

faby
faby

Reputation: 7558

I think that the problem is in this line

for (int i = 0; i < Session.Count; i++)

session always contains others parameters

compare Session.Count with z in GenerateButton_Click method. I suppose that they are differents

Upvotes: 1

Related Questions