Tech
Forums
Jobs
Books
Events
Live
Interviews
More
Learn
Training
Career
Members
Videos
News
Blogs
Login
Sign Up
Ask Question
5
Reply
Add/remove user controls programaticaly to placeholder
Jordan Trajkov
Sep 20 2016 2:53 PM
286
Reply
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--;
}
}
Upload Source Code
Select only zip and rar file.
Post
Reset
Cancel
Answers (
5
)
Next Recommended Forum
Basic keyword in c#
How to make function for dynamicly add/remove controls