[RESOLVED] unable to handle dynamically added usercontrol events
guys i hav a user control which has its own events defined in itself.
it works fine when i add the user control in page_load method of a page ,then the usercontrol defined event handling methods are called but when i add the user control dynamically in a page then the user controls does not calls its handling events...
i want the user control to call its defined event handling methods in dynamic addition tooo...somebody please help me..
here are the files required
check the bold regions in program codes for quick access to specific regions of concern
code behind file in C# using the user control
Code:
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 editQuestion : System.Web.UI.Page
{
Control c1;
protected void Page_Load(object sender, EventArgs e)
{
// c1 = LoadControl("./MCQ.ascx");
//Panel2.Controls.Add(c1);
}
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
if(DropDownList3.SelectedIndex == 1)
{
AccessDataSource1.SelectCommand = "SELECT DISTINCT [ID],[Title] FROM [type1]";
}
if(DropDownList3.SelectedIndex == 2)
{ AccessDataSource1.SelectCommand = "SELECT DISTINCT [ID],[Title] FROM [type2]"; }
if(DropDownList3.SelectedIndex == 3)
{ AccessDataSource1.SelectCommand = "SELECT DISTINCT [ID],[Title] FROM [type3]"; }
//DropDownList1.
}
MCQ c;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// Response.Write(DropDownList1.SelectedValue);
if (DropDownList3.SelectedIndex == 1)
{
c = (MCQ)LoadControl("./MCQ.ascx");
AccessDataSource2.SelectCommand = "SELECT DISTINCT [ID],[Title], [Choices] FROM [type1] WHERE ([ID] =" + DropDownList1.SelectedValue + ")";
DataView dv = new DataView();
dv = (DataView)AccessDataSource2.Select(DataSourceSelectArguments.Empty);
//Response.Write(dv.ToTable().Rows[0].ItemArray[0] + " **** " + dv.ToTable().Rows[0].ItemArray[1]);
// c.setTextbox1((dv.ToTable().Rows[0].ItemArray[1]).ToString());
// c.setTextbox2((dv.ToTable().Rows[0].ItemArray[2]).ToString());
// c.ID=Convert.ToInt32((dv.ToTable().Rows[0].ItemArray[0]));
// c.edit = true;
// c.b.Click += new EventHandler(this.b_Click);
PlaceHolder1.Controls.Add(c);
}
if (DropDownList3.SelectedIndex == 2)
{
MCQ2 c = (MCQ2)LoadControl("./MCQ2.ascx");
AccessDataSource2.SelectCommand = "SELECT DISTINCT [Title], [Choices] FROM [type2] WHERE ([ID] =" + DropDownList1.SelectedValue + ")";
DataView dv = new DataView();
dv = (DataView)AccessDataSource2.Select(DataSourceSelectArguments.Empty);
//Response.Write(dv.ToTable().Rows[0].ItemArray[0] + " **** " + dv.ToTable().Rows[0].ItemArray[1]);
c.setTextbox1((dv.ToTable().Rows[0].ItemArray[0]).ToString());
c.setTextbox2((dv.ToTable().Rows[0].ItemArray[1]).ToString());
Panel2.Controls.Add(c); // here is the user control added to the panel in page......
}
if (DropDownList3.SelectedIndex == 3)
{
Textbox c = (Textbox)LoadControl("./Textbox.ascx");
AccessDataSource2.SelectCommand = "SELECT DISTINCT [Title], [Choices] FROM [type3] WHERE ([ID] =" + DropDownList1.SelectedValue + ")";
DataView dv = new DataView();
dv = (DataView)AccessDataSource2.Select(DataSourceSelectArguments.Empty);
//Response.Write(dv.ToTable().Rows[0].ItemArray[0] + " **** " + dv.ToTable().Rows[0].ItemArray[1]);
c.setTextbox1((dv.ToTable().Rows[0].ItemArray[0]).ToString());
//c.setTextbox2((dv.ToTable().Rows[0].ItemArray[1]).ToString());
Panel2.Controls.Add(c);
}
if (DropDownList3.SelectedIndex == 4)
{
Textbox22 c = (Textbox22)LoadControl("./Textbox22.ascx");
AccessDataSource2.SelectCommand = "SELECT DISTINCT [Title], [Choices] FROM [type2] WHERE ([ID] =" + DropDownList1.SelectedValue + ")";
DataView dv = new DataView();
dv = (DataView)AccessDataSource2.Select(DataSourceSelectArguments.Empty);
//Response.Write(dv.ToTable().Rows[0].ItemArray[0] + " **** " + dv.ToTable().Rows[0].ItemArray[1]);
c.setTextbox1((dv.ToTable().Rows[0].ItemArray[0]).ToString());
c.setTextbox2((dv.ToTable().Rows[0].ItemArray[1]).ToString());
Panel2.Controls.Add(c);
}
}
}
user control
Code:
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;
using System.Data.OleDb;
public partial class MCQ : System.Web.UI.UserControl
{
//public Button b;
OleDbConnection conn;
string count="SELECT COUNT(ID) FROM type1";
int count1;
OleDbCommand res;
public bool edit = false;
public int ID = 0;
public void setTextbox1(String s)
{
TextBox1.Text = s;
}
public void setTextbox2(String s)
{
TextBox2.Text = s;
}
protected void Page_Load(object sender, EventArgs e)
{
// b = Button1;
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source="+Server.MapPath("db1.mdb") );
// conn = new OleDbConnection(s);
conn.Open();
res = new OleDbCommand(count, conn);
OleDbDataReader read= res.ExecuteReader();
read.Read();
count1 =read.GetInt32(0);
//this.butt
Button1.Click+=new EventHandler(Button1_Click);
}
public void Button1_Click(object sender, EventArgs e)-- the button event handler in the user control
{
if (TextBox2.Text.Length == 0)
{
Response.Write("<script language = 'Javascript'>alert('INVALID INPUT');window.location.href = 'quest.aspx?control=MCQ'</script>");
// System.Threading.Thread.Sleep(1000);
//Server.Transfer("quest.aspx?control=MCQ");
//Response.Redirect("quest.aspx?control=MCQ");
}
else
{
/////////////////////////////////////////////////////////////////////
String question;
question = TextBox1.Text;
String temp = TextBox2.Text;
temp = temp.Replace('\r', ' ');
string[] temp2 = temp.Split(new char[] { '\n' });
int choices = temp2.Length;
int i = 0;
String choicestore = "";
while (i < temp2.Length)
{
String ch = temp2[i];
int len = temp2[i].Length;
if ((i + 1) != temp2.Length)
choicestore += ch + ",";
else
choicestore += ch;
i++;
}
String query2 = "";
if (!edit)
{
query2 = "INSERT INTO type1 VALUES(" + (count1 + 1) + ",'" + question + "'," + choices + ",'" + choicestore + "');";
ID = count1 + 1;
}
else
{
query2 = "UPDATE type1 set Title='"+question + "',Choices='" +choicestore + "' WHERE ID="+ID+");";
}
res = new OleDbCommand(query2, conn);
res.ExecuteNonQuery();
conn.Close();
Response.Write("<script language = 'Javascript'>alert('Question added to database successfully');window.location.href = 'main.aspx'</script>");
//Response.Redirect("main.aspx");
//////////////////////////////////////////////////////////////////////
}
}
}
the button event handler is not called when i click on button in aspx page in which it is added infact the submit causes the user control to dissapear...and when i add in load method of page it works fine kindly some one help me..
i had also added the screen shot of the user control
Last edited by vikrant3mahajan; July 23rd, 2009 at 12:45 AM.
Reason: additional information
Not sure what you're trying to achieve by doing this. It may also be possible to approach this problem from another angle as well if you cannot get it to work.
Originally Posted by vcdebugger
the filename you have given contains .ascx extension along with .cs , does that mean it is a asp ? or purely c#?
Yes .ascx.cs is an extension for websites made in ASP. It's the code behind file for a control.
Last edited by monalin; July 23rd, 2009 at 12:11 PM.
Reason: grammer :-)
Re: unable to handle dynamically added usercontrol events
This is one of the deep issues with .NET and it stems back to the Page Life Cycle model, but unfortunately it is very difficult to help you with, so I can't provide any direct answers.
However very simplified; then event handling is done after Page Load. That means to actually handle events on dynamically created controls you must make sure the controls are there when the page is recreated on postback. And it usually isn't when you add it dynamically.
Take a look here for an overview of the cycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx
It can perhaps also help you understand the events
There are many tricks and methods of solving the problems depending on specific implementations. One of the less pretty, but relative fast ones are to call the "__doPostBack('','')" javascript with custom eventtarget and eventarguments and then read them via Request.Form in the PageLoad and handle it manually.
That is why it is usually not optimal to assign controls dyamically because event handling in it can be very tricky and confusing.
If you need to add controls dynamically - I would actually reevaluate the requirements and see if you can design another solution, perhaps with more pages with no dynamic controls or similar.
Or have the controls always on the page, and then just set visible to false which ensures the controls are there to bind the event on. And so on.....
But there are as many solutions as there are problems, so it is difficult to help with (short of making the project for you), because it is the "under-the-hood" fundamentals of asp.net.
Re: unable to handle dynamically added usercontrol events
I agree with Alsvha. Using dynamically created controls always gets messy. I almost always try to avoid doing it in my websites. Normally what is put multiple controls on the page and hide the ones I don't want showing. It all goes back to what I said originally, there might be some other way to implement your code that do not require creating dynamic user created controls.
It is not impossible though to do what you're attempting to do. It just might not be worth your time to try and sort it all out if there is another way to go about implementing your project.
Re: unable to handle dynamically added usercontrol events
thnx for your replies and time guys really thanx...i went through all your posts and links...and i found the mistake..the problem was the postback..the control was not loaded on postback and i loaded the control again in page_load...this solved the prob as it reloaded in each postback as in each postback page_load is called again.....
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.