I have a dynamically created table and in some of the cells i have an image button associated with the redBall_Click() handler
(here is the code behind)
TableCell cellOK = new TableCell();
cellOK.Style.Add(HtmlTextWriterStyle.TextAlign, "Center");
cellOK.Width = new Unit("3%");
ImageButton redBall = new ImageButton();
redBall.CausesValidation = false;
redBall.ID = id;
redBall.ImageUrl = "~/App_Themes/DotRed.png";
redBall.Click += new ImageClickEventHandler(redBall_Click);
cellOK.Controls.Add(redBall);
My problem is that the redBall_Click() method is never called (neither after the PostBack)
How can i solve this?
P.S. : I can't use a static link because every ImageButton is associated with a specific ID that i must pass to the page i call (for example as a Session object)
You have to set up the event handler within OnInt and do it every time the page is created, even during a postback. Make sure you don't have the code within a block like:
if(!this.IsPostback)
{
...
}
Have you tried putting a breakpoint in the page load method before clicking the image? I suspect this might show that the postback is happening, even if the image click handler isn't getting fired.
Is the code to create the image button also invoked during a postback? If not, the page will postback, but the image button won't exist to invoke the click handler. Sounds bizarre, but it's caught me out a few times.
I finally resolved (just yesterday).
I guess I was building my buttons too late: in the Page_PreRender (after the event was to be fired) maybe if i put the creation in Page_Load (yes, I create everything also on PostBack) it would handle the click, but I think I won't try since I found a workaround.
I'll explain for anyone who could have the same problem:
private TableCell cellOK(string id)
{
TableCell cellOK = new TableCell();
cellOK.Style.Add(HtmlTextWriterStyle.TextAlign, "Center");
Image redBall = new Image();
redBall.ID = id; // useless
redBall.ImageUrl = "redball.gif";
HyperLink hl = new HyperLink();
hl.Controls.Add(redBall);
hl.NavigateUrl = MyPage + "?id=" + id;
cellOK.Controls.Add(hl);
return cellOK;
}
and in Page_Init()
string m_QueryStringId = Request.QueryString.Get("id");
if (!string.IsNullOrEmpty(m_QueryStringId))
{
// Do something
}
Related
Here is what a portion of my screen looks like:
The user can pick a choice from the drop-down list and click the add button. Here is the code for the add button:
protected void btnModuleAdd_Click(object sender, EventArgs e)
{
var selectedModule = ddlModsList.SelectedItem.ToString();
var graphicName = this.GraphicName;
var xr = new GraphicModuleXRef();
xr.GraphicName = graphicName;
xr.Module = selectedModule;
// Take drop down list selection and add it to GraphicModuleXRef table.
var context = new XRefDataContext();
context.GraphicModuleXRefs.InsertOnSubmit(xr);
context.SubmitChanges();
}
Basically, it's taking the user's choice and writing it out to a table. This part works fine.
In my Page_Load, I check whether IsPostback and, if it is, I run the code below:
private void LoadOtherModulesUsed()
{
if (this.GraphicName != null)
{
lbModules.Items.Clear();
var context = new XRefDataContext();
var q = context.GraphicModuleXRefs
.Where(a => a.GraphicName.Contains(this.GraphicName));
foreach (GraphicModuleXRef gr in q)
{
lbModules.Items.Add(new ListItem(gr.Module.ToString()));
}
}
}
This code reads from a table, finds all records that match the criteria, and adds them to the listbox.
So, what I'm expecting to happen is for the page to reload and the listbox to be repopulated, including the new entry just added to the table. But, that isn't happening. The screen refreshes like it has reloaded, but the entry doesn't appear in the listbox. However, it IS there, it just can't be seen. If the user adds another entry, by clicking the Add button, the list 'rolls up' one row and the previous entry can be seen. But, not the new one. If the user exits from the screen and re-enters, all the entries in the listbox can be seen. It's almost like the listbox is too short to display all records, but I've tried different heights, with no difference.
I'm wondering if anyone can point me in the right direction?
Put simply, when adding a new item to the listbox, it isn't immediately visible unless another item is added, thereby 'rolling' the list up. Even scrolling the list with the scrollbar doesn't show the new entry until another entry is added. And, if you scroll the list up, you can see the prior entry. So strange!
EDIT: Trying to describe this more simply:
User adds item to listbox by pressing Add button.
New item does not appear in listbox.
User adds another item to listbox by press Add button.
Prior item now shows in listbox if user scrolls listbox up.
The newest item just added, however, does not appear unless step 3 is repeated.
Also, exiting the page and then coming back in loads every item in the list and all is visible.
This is a timing issue. Whats happening is Page_Load runs first in this case and THEN the Click event handler so effectively the control has been bound before the new entry is added. Thats why you're always one refresh behind. Id refactor your code like this so everything runs in the correct order! To understand the timing of event execution I strongly recommend reading this article on MSDN its AWESOME and will really help you get the best from ASP.NET.
Additionally reading this article on MSDN (Also awesome) especially the section on ViewState will explain how the DropDown retains its details even when, in the modified code, you're onlly filling it when the page is NOT a postback and when the click event is fired.
Hope this helps!
public void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
LoadOtherModulesUsed();
}
private void LoadOtherModulesUsed()
{
if (this.GraphicName != null)
{
lbModules.Items.Clear();
var context = new XRefDataContext();
var q = context.GraphicModuleXRefs
.Where(a => a.GraphicName.Contains(this.GraphicName));
foreach (GraphicModuleXRef gr in q)
{
lbModules.Items.Add(new ListItem(gr.Module.ToString()));
}
}
}
protected void btnModuleAdd_Click(object sender, EventArgs e)
{
var selectedModule = ddlModsList.SelectedItem.ToString();
var graphicName = this.GraphicName;
var xr = new GraphicModuleXRef();
xr.GraphicName = graphicName;
xr.Module = selectedModule;
// Take drop down list selection and add it to GraphicModuleXRef table.
var context = new XRefDataContext();
context.GraphicModuleXRefs.InsertOnSubmit(xr);
context.SubmitChanges();
LoadOtherModulesUsed();
}
I am generating a linkbutton dynamically and setting its postbackurl by iterating over a collection the linkbutton shows the correct url when i hover mouse over it but when i click the linkbutton only three of intended five querystring parameters are passed.
I,m using Firefox
here's my code
foreach(var item in collection)
{
linkbutton b = new linkbutton();
linkbutton.postbackurl="somepage.aspx?" + "param1="+ item.val1 + "¶m2=" + item.val2
+ "¶m3=" + item.val3+ "¶m4=" + item.val4+ "¶m5="
+item.val5;
PlaceHolder1.Controls.Add(b);
}
however when i click the linkbutton browser opens
somepage.aspx?param1=val1¶m2=val2¶m5=val5
all values are present in the collection item
plus the browser ignores param3,4 in the link itself
:<
once again HELP!!!
For this scenario you just need an asp:HyperLink not need of a asp:LinkButton. There are some errors in your code. A more optimised / readable version will be this
foreach(var item in collection)
{
var btn = new HyperLink();
btn.NavigateUrl=String.Format("somepage.aspx?param1={0}¶m2={1}¶m3={2}¶m4={3}¶m5={4}",
item.val1,
item.val2,
item.val3,
item.val4,
item.val5);
PlaceHolder1.Controls.Add(btn);
}
Hope this helps.
I am using the dropdown-check-list plug-in to create a dropdownlist that allows multiple selection.
However, it is getting duplicated in every postback after it has been used, which produces something like this:
Does anyone know why this is happening and how to fix it?
UPDATE: About the request to show some code:
Javascript:
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(load_lazyload);
load_lazyload();
...
}
function load_lazyload() {
$("#ContentPlaceHolder1_userControl1_listBoxMultiValueNumbers").dropdownchecklist();
...
}
C#: this is how the listBox is being populated:
listBoxMultiValueNumbers.DataTextField = ds.Tables[0].Columns["number"].Caption;
listBoxMultiValueNumbers.DataValueField = ds.Tables[0].Columns["number"].Caption;
listBoxMultiValueNumbers.DataSource = ds;
listBoxMultiValueNumbers.DataBind();
listBoxMultiValueNumbers.Items.Insert(0, new ListItem("Select numbers", "-1"));
UpdatePanelUCCNFT.Update();
i think you have load your dropdown on page load without using postback event..that's why its binding everytime..
use page_load()
{
if(!ispostback)
{
//load your dropdown here
}
}
I don't if you still have the problem or not. I just encountered similar problem where I had, dropdownlist gets duplicating after every postback. This solved my problem
fillDropDownList()
{
String selectValue = DropDownList.SelectedValue();
DropDownList.Items.Clear(); // to clear the duplicates
DropDownList.SelectedValue = selectValue; // to restore previously selected value
DropDownList.Items.Insert("0", New ListItem(" Select ", ""));
DropDownList.DataBind();
}
in the page_load
if (Page.IsPostBack)
{
fillDropDownList();
}
I hope this helps!
You're calling the load function twice, thus getting two drop downs. Once registered with ...add_endRequest(load_lazyload) and again explicitly. I'd guess if you remove the call to add_endRequest it would fix it (after all, you already have it wrapped in $(document).ready())
I have a page with a MultiView control, and some of the views are long enough to scroll. Since may of the controls in the reviews require postback to function properly, MaintainScrollPositionOnPostBack is enabled on the page.
I have a problem when the user transitions from one view to another. If they were at the bottom of a long view, and transition to another long view, the new view loads and is scrolled all the way to the bottom. I need to jump to the top of the page when the user goes to a new view within the MultiView.
I've tried using the OnActiveViewChanged event to:
- call RegisterStartupScript to set window.location.hash to an anchor that I placed at the top of the page.
- call RegisterStartupScript to call window.scrollTo(0,0)
- set MaintainScrollPositionOnPostBack to false temporarily
The problem is that none of these seem to affect the actual transition postback, they take effect on the next postback, which actually causes a bigger issue.
Anybody have a proven method to have a MultiView page jump to top of page only on postbacks that transition to a new view?
This is exactly the same problem I've been having today with a multiview.. I found your question and went looking for answers. Seems we found the same article!
(Article code in C#)
private void ResetScrollPosition()
{
if (!ClientScript.IsClientScriptBlockRegistered(this.GetType(), "CreateResetScrollPosition"))
{
System.Text.StringBuilder script = new System.Text.StringBuilder();
script.Append("function ResetScrollPosition() {");
script.Append(" var scrollX = document.getElementById(\'__SCROLLPOSITIONX\');");
script.Append(" var scrollY = document.getElementById(\'__SCROLLPOSITIONY\');");
script.Append(" if (scrollX && scrollY) {");
script.Append(" scrollX.value = 0;");
script.Append(" scrollY.value = 0;");
script.Append(" }");
script.Append("}");
//Create the ResetScrollPosition() function
ClientScript.RegisterClientScriptBlock(this.GetType(), "CreateResetScrollPosition",
script.ToString(), true);
//Add the call to the ResetScrollPosition() function
ClientScript.RegisterStartupScript(this.GetType(), "CallResetScrollPosition", "ResetScrollPosition();", true);
}
}
Found an answer/workaround, finally: 4Guys
You have to trick ASP.Net into doing it for you by manipulating the hidden fields it uses for tracking the scroll position.
I am building a dynamic user control (ascx) which contains a placeholder. Inside the placeholder, there will be n tables. Inside each table, in one of the cells i have the link button as below.
HyperLink lnkButton = new HyperLink();
lnkButton.ID = "lnkButton_" + ID.ToString();
lnkButton.Text = tstText;
lnkButton.NavigateUrl = "javascript:JS_Click();";
I have to call a JS function on the link button click (no postback).
In the JS function, i have to get the id of the control that invoked that JS function. In this case, it will be link button. I am writing the below code in the JS Function:
var ctrl = event.srcElement.id;
but i am getting 'Object Required' error in javaScript.
Few other things: This user control will be loaded in default.aspx page and the JS Function i am writing in default.aspx.
I am not sure why this is not working. I am using IE6/7, VS 2005. Is there any other function or way available to get the srcElement.id. Please help.
Try passing this along when you invoke the method
lnkButton.NavigateUrl = "javascript:JS_Click(this);";
then you can write this in your JS_Click event
function JS_Click(obj)
{
alert("Now I have my object " + obj.id);
}
Another option would be to use jQuery and wire up to the click event on your link buttons.
Add a CssClass attribute to the LinkButton's you are creating:
HyperLink lnkButton = new HyperLink();
lnkButton.ID = "lnkButton_" + ID.ToString();
lnkButton.Text = tstText;
lnkButton.CssClass = "linkButton";
Then write the follwoing JS/ JQuery in your ASPX page:
$(document).ready(function()
{
$('.linkButton', '#userControlID').click(function(e)
{
alert('You clicked linkbutton with ID ' + e.target.id);
});
});
In the above example each link button has class="linkButton" and they are contained within your usercontrol with ID="userControlID".