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.
Related
protected void lbChatFriend_Click(object sender, EventArgs e)
{
ChatDivContent.Visible = true;
System.Web.UI.HtmlControls.HtmlGenericControl createDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
createDiv.ID = "div";
createDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Yellow");
createDiv.Style.Add(HtmlTextWriterStyle.Position, "relative");
createDiv.Style.Add(HtmlTextWriterStyle.Color, "Red");
createDiv.Style.Add(HtmlTextWriterStyle.Height, "50px");
createDiv.Style.Add(HtmlTextWriterStyle.Width, "50px");
createDiv.InnerHtml = " I'm a div ";
string chatFriend = ((LinkButton)sender).Text;
createDiv.Attributes["title"] = chatFriend;
ChatDivContent.Controls.Add(createDiv);
}
<div id="ChatDivContent">
<DIV id="div" style="background-color:Yellow;position:relative;color:Red;height:50px;width:50px;"
title="dinesh"> I'm a div </DIV></div>
<----This is my output on every postback
Wnat am I doing wrong?
I assume that you're not recreating the old controls on postback(f.e. when the user clicks on that LinkButton). Therefor only the recently created div is displayed.
You have to recreate all dynamically created controls on every postback(in load event at the latest).
You also have to ensure that they get the same ID as before to trigger events and maintain ViewState.
If you know the number of controls to create(which could be stored in ViewState) you can derive the ID from the counter variable by appending it to the control-id. Then you can recreate them with the correct ID in page's init event.
Recommandable readings:
TRULY Understanding Dynamic Controls
Page-Lifecycle
Or you use one of the builtin Data-Bound Control like Repeater that do this automatically. You only have to set their DataSource and call DataBind().
Here is an answer of me on a similar question with implementation.
Following is the scenario I am facing, I have a aspx page in which I have added my ascx user control, I also have a <a href control which call a js function to open a aspx popup.
when I open the popup, I need to send the data present in the ascx control to my popup. can you please guide me what method can I use to achieve this other than using session, as the data can be updated in many different places hence maintaining in session will be difficult.
Thanks
try with these syntaxe ( RegisterStartupScript + window.open)
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "newWindow", "window.open('Test.aspx?ID=" + _cId + "','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30);", false);
You said that you are using a js function to open the aspx popup.
then it is simple.
1. Read the Data from the controls of the User control by using javascript
var variable1 = document.getElementByID("ControlId").value;
var variable2 = document.getElementByID("ControlId").value;
2. Pass this data as query string to the next page
window.open("http://www.w3schools.com?id=" + variable1 + "&name=" + variable2);
You can read this data from querystring from the next page
If you cant sent data as querystring , can try some other ways
1. Try to post the form to the other page using target="_blank".
we can dynamically change the form action if needed.
OR
2. Make use of the window.opener object from the popup to read the data from controls the opener page.
var variable1 = window.opener.getElementById("ControlId").value
Create a hidden variable in your ascx.
<asp:HiddenField runat="server" ID="hdnId" />
On page load of ascx set the value to be sent to the hidden variable
protected void Page_Load(object sender, EventArgs e){
hdnId.Value = <value to be sent to pop-up>;
}
Register a ajax manager in the code behind.
protected override void OnInit(EventArgs e)
{
RadAjaxManager.GetCurrent(this.Page).ClientEvents.OnRequestStart = "ajaxMngr_RequestStart;";
base.OnInit(e);
}
In the ajaxMngr_RequestStart() JS
function ajaxMngr_SA_RequestStart(sender, args) {
var oPatId = "<%=hdnSendPatId.Value %>";
//add code to open the pop-up, add oPatId as part of the URL
}
}
I use Telerik, which makes helps a lot in managing pop-ups. Let me know, if this helps.
Cheers!
I have the following ASP.NET code:
<div id="panelIssue" runat="server" style="width: 450px; height: 320px;">
<gsl:IssueUC ID="ucIssue" runat="server"
OnItemSaved="ucIssue_ItemSaved"
OnItemCancelled="ucIssue_ItemCancelled" />
</div>
and then have an asp:Button on the page that simply call some methods and set some properties of the custom user control like
protected void btnNewIssue_Click(object sender, EventArgs e) {
ucIssue.ChangePanelMode(PanelModeEnum.Add);
ucIssue.FirmID = Convert.ToInt32(Page.Session["FirmID"]);
ucIssue.loadObject();
}
I know that I can use the div to show a jquery modal dialog but the question is how to set the usercontrol properties and call their methods?
I can evaluate also a different approach (e.g. changing the usercontrol).
Thanks in advance
Lorenzo
What I can suggest is that in the click event, after setting the control properties, you can emit a piece of javascript that will create and display a modal when the page finishes loading upon reaching the client.
Try something along the lines of the following snippet (not tested, may need small tweaking to work, but I hope you get the big idea):
protected void btnNewIssue_Click(object sender, EventArgs e) {
ucIssue.ChangePanelMode(PanelModeEnum.Add);
ucIssue.FirmID = Convert.ToInt32(Page.Session["FirmID"]);
ucIssue.loadObject();
//emit client script that will create and show the modal dialog
ClientScriptManager clientScriptManager = Page.ClientScript;
string scriptText = "$(document).ready(\n" +
"function() {\n" +
"$('#panelIssue').dialog({\n" +
"autoOpen: false,\n" +
"modal: true,\n" +
"width: 450,\n" +
"height: 320,\n" +
"title: \"Some title\",\n" +
"resizable: false,\n" +
"draggable: false });\n" +
"$('#panelIssue').dialog('open');\n" +
"});";
clientScriptManager.RegisterClientScriptBlock(this.GetType(), "MyScript", scriptText, true);
}
You should also look at the capabilities of the dialog creation in jQuery to see what other settings will fit your scenario better. I just used a few of the params that I have in an example of mine.
I have an ASP.net application with an aspx page.
In Page_Load event of the aspx page, I'm handling some code which is based on the value of a hidden variable from the javascript(assigning result of javascript to hidden variable).
I am calling the javascript in Page_Load of the child page, and in the immediate statement, I'm making use of the hidden variable value for processing. When I access hidden variable value, I'm getting default value only.
Please suggest me any of handling the scenario. I need to execute the javascript and get the result into the hidden variable. Both in need to occur in Page_Load event only.
Hidden Variable declaration:
<asp:HiddenField runat='server' ID='hdnDate' Value='0' />
Javscript:
function getCDate() {
var nowDate = new Date();
var curr_month = nowDate.getUTCMonth();
curr_month ++;
var dt = curr_month + "/" + nowDate.getUTCDate() + "/" +nowDate.getFullYear()+ " " + nowDate.getUTCHours()+":" +nowDate.getUTCMinutes()+":" +nowDate.getUTCSeconds();
document.getElementById("ctl00_ContentPlaceHolder1_hdnDate").value = dt;
return true;
}
Page_Load method in code behind file:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "getCDate();", true);
DateTime dt=Convert.ToDateTime(hdnDate.Value);
dt.AddDays(10); //getting error here because dt contains01/01/0001
}
You cannot call javascript in Page_Load. It is client side thing so should come from browser only. You can check if page is postback using IsPostBack property of Page object like this:
if(IsPostBack)
{
//this is coming from browser so you javascript might have been
//called and proper value set in hidden field.
}
Javascript is run on the client side, so can't run in the Page_Load event on the Server.
From the looks of your code, I'm pretty sure you don't need javascript, you can just put the value into a SessionVariable as:
Session.Add("DateRendered", DateTime.Now.AddDays(10).ToString("MM/dd/YYYY"));
And then retrieve it later. ASP.net takes care of storing it in the Request/Response.
RegisterStartupScript will register your block of script for the next page load.
if you just want some value to be transferred to .cs page write a static method on the .cs and call it from javascript using PageMethods.MethodName();
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.)