TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Jordan Trajkov
1.6k
163
10.5k
Add/remove user controls programaticaly to placeholder
Sep 20 2016 2:53 PM
I make one asp.net web forms app, I create user control, in this user control I insert few standard .net controls. Now in my page.aspx I want dynamicly to insert this user control. I put a button, something like "Add new control".
If I click on it I'm adding a new control to the page. And all this works fine.
I have a problem in removing of this controls. I write a function for removing. But first time when I click it doesn't remove the control, I have to click another time to remove the last control. I think is something with postback, don't know why at first post back it doesn't remove the control.
I'm addding programaticly controls to PlaceHolder which is inside UpdaPanel. Here is the c# code how i do this, pls anybody knows where i make mistake?
public
partial
class
Clasess_And_Events : System.Web.UI.Page
{
protected
int
NumberControlsForCategory
{
get
{
return
(
int
)ViewState[
"NumControlsForCategory"
]; }
set
{ ViewState[
"NumControlsForCategory"
] = value; }
}
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(!IsPostBack)
{
//Initiate the counter of dynamically added controls
this
.NumberControlsForCategory = 0;
}
else
{
//Controls must be repeatedly be created on postback
this
.createControlsCategory();
}
}
private
void
createControlsCategory()
{
int
count =
this
.NumberControlsForCategory;
for
(
int
i = 0; i < count; i++)
{
Control myUserControl = (Control)Page.LoadControl(
"UserControls/CategoryDropdown.ascx"
);
myUserControl.ID =
"CategoryControl_ID_"
+ i.ToString();
PlaceHolder1.Controls.Add(myUserControl);
}
}
protected
void
Add_Controll_Click(
object
sender, EventArgs e)
{
Control myUserControl = (Control)Page.LoadControl(
"UserControls/CategoryDropdown.ascx"
);
myUserControl.ID =
"CategoryControl_ID_"
+ NumberControlsForCategory.ToString();
PlaceHolder1.Controls.Add(myUserControl);
this
.NumberControlsForCategory++;
LinkButton10.Visible =
true
;
}
protected
void
Remove_Control_Click(
object
sender, EventArgs e)
{
Control myUserControl = (Control)Page.FindControl(
"CategoryControl_ID_"
+ NumberControlsForCategory.ToString());
PlaceHolder1.Controls.Remove(myUserControl);
this
.NumberControlsForCategory--;
}
}
Reply
Answers (
5
)
Basic keyword in c#
How to make function for dynamicly add/remove controls