I have a page that dynamic create a table of contacts, if the contact got an email I also create an image button with a click event.I have a similar function in the rest of the page that works perfectly. And I used this before without any problems:
protected void CreateContactsList(IQueryable<AA_BranschFinder.Login.vyWebKontaktpersoner> lContacts) // Creates a table in the aspx from an IQueryable List
{
if (1 == 1)
{
htmlTblContactsContent.Rows.Clear();
foreach (var p in lContacts)
{
HtmlTableRow tr = new HtmlTableRow();
HtmlTableCell tdName = new HtmlTableCell();
HtmlTableCell tdCompanyName = new HtmlTableCell();
HtmlTableCell tdEmailAdress = new HtmlTableCell();
tdName.InnerHtml = p.strFnamn + " " + p.strEnamn;
tdCompanyName.InnerHtml = p.strNamn;
//Displays an image if the contacts has an email
if (p.strEpost != null)
{
ImageButton imgEmail = new ImageButton();
imgEmail.CommandArgument = p.intKundID.ToString();
imgEmail.ImageUrl = "images/symbol_letter.gif";
imgEmail.CssClass = "letter";
imgEmail.Click +=new ImageClickEventHandler(imgEmail_Click);
tdEmailAdress.Controls.Add(imgEmail);
}
tr.Cells.Add(tdCompanyName);
tr.Cells.Add(tdEmailAdress);
tr.Cells.Add(tdName);
htmlTblContactsContent.Rows.Add(tr);
}
}
}
void imgEmail_Click(object sender, ImageClickEventArgs e)
{
Breakpoint here
throw new NotImplementedException();
}
The page is living inside a java popup window. But I have paging numbers with similar event creation that works fine. But they are Linkbuttons.
Where are you calling your Create method? You need to do it before the other event handlers run, ideally in the Page.Init. Otherwise, the data posted back to the page are indicated an event firing for a control that doesn't yet exist.
I would also make sure that you give your ImageButton an ID. It will make debugging a lot easier.
imgEmail.ID = String.Format("EmailImageButton_{0}", p.intKundID);
An alternative solution is to look at the __eventtarget and __eventargument parameters in the Request object and see which button was clicked there.
You'll have to create the dynamic controls on EVERY postback. Also check the code in the imgEmail_Click event handler; if you have created the event handler method using .NET IDE's Alt + Shift + F10 method, then there's a chance that you have not removed this line -
throw new Exception("The method or operation is not implemented.");
If I´m not misstaking the imagebutton is a submit kind of button while the linkbutton is an a-tag with javascript. Maybe changing your imagebutton click (ie usesubmitbehaviour set to false) will solve your problem.
Make sure the event handler is added on your postbacks. When adding it just on initial page load, the event won't be handled! (Just encountered and solved this problem myself.)
Related
I'm developing live-table with WebForms.
I'm adding such control to each TableCell in each TableRow, when I'm adding new rows to the table:
// in some method, which creates the table
TableRow row = new TableRow();
// here goes other cells with text data
TableCell cellActions = new TableCell();
cellActions.ID = "offerActionsOfferId" + enumerator.Current.offerId;
// init button View More for cell
LinkButton buttonViewExpanded = new LinkButton();
buttonViewExpanded.ID = "buttonViewExpandedOfferId" + enumerator.Current.offerId;
buttonViewExpanded.CssClass = "table-actions-button ic-table-edit";
buttonViewExpanded.Click += new EventHandler(buttonViewExpanded_Click);
buttonViewExpanded.ToolTip = "some alt...";
cellActions.Controls.Add(buttonViewExpanded);
/* end of Action Buttons */
...
row.Cells.Add(cellActions);
this.tableMarket.Controls.Add(row);
But there is a fail with the new EventHandler(buttonViewExpanded_Click) method.
Table renders in the ASPX page pretty well and all controls are visible, but a fail occurs when I try to click that LinkButton.
When I've marked a breakpoint and try to catch the execution of my ASP.NET program in the debugger to make some analyse of program work - the page only refreshed and no one breakpoint in the click event handler has been caught.
Why does it occur? And how to make it work?
I cannot test your code; it ties to other classes like InternalApi. However, here is what I found.
You need to figure out the way to load SetTableBodyForSceneMarket in page init.
It basically reload dynamically created controls on post back; otherwise, those controls will be null, and cannot fire events.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if(IsPostBack)
{
SetTableBodyForSceneMarket();
}
}
private void SetTableBodyForSceneMarket()
{
...
}
I've created an application in which I've created Dynamic Controls on Click Event of a Button. But the dynamically created Control Event will not Fire on Click of it.
Below is the Code I've written.
ImageButton closeImage = new ImageButton();
closeImage.ID = "ID"+ dr["ID"].ToString();
closeImage.AlternateText = "Delete";
closeImage.ImageUrl = "App_Themes/images/CloseButton.png";
closeImage.Attributes.Add("style", "float:right;cursor:pointer;margin: -19px 1px -10px;");
closeImage.EnableViewState = true;
closeImage.CommandName = "Delete";
closeImage.CommandArgument = dr["ID"].ToString();
closeImage.Attributes.Add("runat", "server");
closeImage.OnClientClick = "return confirm('Are you sure you want to remove this');";
closeImage.Click += new ImageClickEventHandler(this.closeImage_click);
protected void closeImage_click(object sender, ImageClickEventArgs e)
{
ImageButton ibDel = (ImageButton)sender;
}
The same code work if its placed on Page_Load(). Is there any other Solution to fire the event.
I would like to suggest that you read up on the following article on MSDN. It's about page lifecycle.The key part is to when controls are created. If the controls are created in the wrong stage, events will not be registered, and thus will not fire.
http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.80%29.aspx
I am working with the .Net List view along with a data pager to enable pagination for a list view.
I am able to set the pagination working perfectly for the list view but I wish to have a method being called when ever the user clicks on any of the page numbers in the data pager.
I want to perform some operation whenever the page number is called. I guess there is no onclick event, so is there any other way by which this is possible.
Thanks
you can set it as imagebutton or linkbutton.
I have piece of code.. you just need to implement it.
you can set link and click event.
foreach (DataPagerFieldItem dpfItem in dtpPaging.Controls)
{
foreach (Control cPagerControls in dpfItem.Controls)
{
if (cPagerControls is ImageButton)
{
ImageButton imgNavigation = cPagerControls as ImageButton;
imgNavigation.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
imgNavigation.Click += new ImageClickEventHandler(imgNavigation_Click);
}
if (cPagerControls is LinkButton)
{
LinkButton lnkNumbers = cPagerControls as LinkButton;
lnkNumbers.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
lnkNumbers.Click += new EventHandler(lnkNumbers_Click);
}
}
}
You can bind a handler to the OnPagePropertiesChanging Event of the List View. A PagePropertiesChangingEventArgs object is passed to the handler as argument which contains MaximumRows and StartRowIndex properties. You can use these to calculate the current page number. It is very easy and requires no code-behind event binding as the solution proposed by sikender.
ive imagebuttons which created in runtime from database and i need to add them onclick or mouseover event but i failed
imagebutton.click += new ImageClickEventHandler(imageButton_Click);
im adding this when i created imagebuttons, what i need else
also i tried javascript but its not firing too;
<script type="text/javascript">
function SetProductImage(imgID) {
document.getElementById('imgProduct').src=document.getElementById(imgID).src;
}
</script>
imgProductImage.Attributes["onclick"] = "javascript:SetProductImage('" + imgProductImage.ID + "')";
thank you...
From your comment I am assuming you are doing something like:
void Page_Load(object s, EventArgs e)
{
ImageButton img = new ImageButton();
img.click += new ImageClickEventHandler(imageButton_Click);
Controls.Add(img);
}
This won't work because the PostBack mechanism sends the Id of the control back in the EventTarget field and the target isn't specified so it doesn't know where to handle it.
To get this to work properly I usually wrap the display in a custom user control and override the CreateChildControls() method. This ensures that the control is created at the correct time and is available when the postback handling is done.
Are you trying to fire up a code behind event? or a javascript event? If you are trying to add a javascript event to your element, you should Add the attribute. It's not currently there when you use: Attributes["onclick"]. So It'd be like:
imgProductImage.Attributes.Add("onclick","SetProductImage('" + imgProductImage.ID + "')");
Ok. I think I found out what you are trying to achieve. You have to explicitly set the ID of the control in Page_Load:
ImageButton img = new ImageButton();
img.ID = "image1";
img.ImageUrl = "YOUR_IMAGE_URL";
img.OnClientClick = "SetProductImage('" + img.ID + "');return false;";
Controls.Add(img);
Just make sure if you have to define multiple image buttones, Set a unique ID for each of them.
We are rendering usercontrols dynamically like this:
public string RenderControl(string pathcontrol)
{
string html;
var page = new Page();
var control = page.LoadControl(path);
page.Controls.Add(control);
// do stuff to the control (give it some data to work on)
using (var writer = new StringWriter())
{
HttpContext.Current.Server.Execute(page, writer, false);
html = writer.ToString();
}
return html;
}
This lets us the same user controls when rendering pages normally as we do when rendering responses to ajax calls. However, when adding controls which themselves contain a scriptmanagerProxy we run into the problem that the newed up Page object doesn't contain either a ScriptManager or the HtmlForm in which the ScriptManager needs to run.
Is there any way around this?
Yours
Andreas
As others have said you can add a ScriptManger dynamically easily enough [ Add ScriptManager to Page Programmatically? if your Page object is complete.
Can you try using BuildManager.CreateInstanceFromVirtualPath() to create the Page object instead? You issue may be how you create that object. There's a bit more to creating a new page than newing up the Page object.
Eg.
Page page
= BuildManager.CreateInstanceFromVirtualPath("~/Test.aspx", typeof(Page))
See also http://www.west-wind.com/weblog/posts/120530.aspx for a little more background.
Can you do something like this:
page.Form.Controls.AddAt(0, New ScriptManager())
Edit: I think you'd also need to add your control to the page's form, not just to the page itself, right? It's my understanding that the form is created with the page, but if not you should be able to just do:
page.Form = new HtmlForm()
You may also need to do something like:
page.Controls.Add(page.Form)
Sure, the trick is to add it in a page's Init event handler. You can use:
Page.Init += delegate {
// check for script manager
if( ScriptManager.GetCurrent(Page) == null ) {
ScriptManager m = new ScriptManager();
m.ScriptMode = ScriptMode.Release;
Page.Form.Controls.AddAt(0, m);
}
}
I'd recommend avoiding dynamically adding forms to your page if you can. For example, the above code snippet assumes a form is already present on the page.
Update
Sure, thanks for pointing that out Andreas. Here's an update. So, there is no setter for Page.Form - but you are correct in that you can add a new HtmlForm to the Controls collection. Once added, the Page.Form property is no longer null. That will allow you to add the ScriptManager dynamically as seen above. Here is a code sample that shows this working (ASPX file is a simple page without a server side form):
public partial class Pages_Test_DynamicFormSample : Page {
protected void Page_Init(object sender, EventArgs e) {
Controls.Add( new HtmlForm() );
ScriptManager m = new ScriptManager();
m.ScriptMode = ScriptMode.Release;
Form.Controls.AddAt(0, m);
}
protected void Page_Load(object sender, EventArgs e) {
// ScriptManager test
var t1 = new System.Web.UI.WebControls.TextBox();
var t2 = new System.Web.UI.WebControls.TextBox();
Form.Controls.Add( t1 );
Form.Controls.Add( t2 );
ScriptManager.GetCurrent(Page).SetFocus( t2 );
}
}
Enjoy - btw, setting the ScriptManager's ScriptMode to Release obviously isn't required. We do it just to avoid some JavaScript bugs found in the Debug version of the ASP.NET script runtime.