index out of range exception

Posted by Rickeybglr under ASP.NET on 11/29/2012 | Points: 10 | Views : 1859 | Status : [Member] | Replies : 1
i have created some controls (textbox, labels) at runtime and added to panel, when i am trying to delete some of the controls from the panel, it throwing index out of range exception. i chekd the index value too.
here is my code:
public static int index = 0;

protected void Page_Load(object sender, EventArgs e)
{ }

protected void add_click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
Panel1.Controls.Add(txt);
index = Panel1.Controls.IndexOf(txt);
}

protected void delete_Click(object sender, EventArgs e)
{
Response.Write(index);
Panel1.Controls.RemoveAt(index);

//i tried with ths code also
// TextBox txt = new TextBox();
// Panel1.Controls.Add(txt);
// // index = Panel1.Controls.IndexOf(txt);
// Panel1.Controls.Remove(txt);
}
}




Responses

Posted by: Sandhyab on: 11/29/2012 [Member] Starter | Points: 25

Up
0
Down
Try Like this
public static int index = 0;


protected void Page_Load(object sender, EventArgs e)
{

}

protected void add_click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "txt";
Panel1.Controls.Add(txt);
index = Panel1.Controls.IndexOf(txt);
}

protected void delete_Click(object sender, EventArgs e)
{
Response.Write(index);
//Panel1.Controls.RemoveAt(index);
Panel1.Controls.Remove(Panel1.FindControl("txt"));


}


Thanks & Regards

Rickeybglr, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response