Category Archives: ImageButton

[RESOLVED] ImageButton always calls page_load event....

I'm using ASP.NET 3.5 and C#.

I load an SqlDataSource into a DataView on my Page_Load event. My SqlDataSource queries a random record from the database. On my page I have an ImageButton, which when clicked uses a Response.Redirect("AnotherPage.aspx + "random id from database"). My problem is that when the button is clicked it fires the Page_Load event before the Response.Redirect takes place in the button_click event. This causes the current data(the users "id") that I had pulled from the database to be overwritten with new data(a different "id") from the database. So essentially the the page is redirecting to the 2nd random id that is queried from the db after the button is clicked and Page_Load is fired again, not the original id. Here's my code, hope it makes sense.

Here's my Page_Load:

DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);


id = dv[0]["Id"].ToString();


Then my Button_Click Event:

protected void btn1_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("~/Profile.aspx?id=" + id1);
    }

Can I put my dataview in another event or method so it's not called when a user clicks an ImageButton. Also I want the DataView to be repopulated on a postback/page refresh, just not on button clicks. How?


Hi,

The page life cycle will work like that only.

In the Page_Load event you need to use Page.IsPostBack checking to ensure that during the post back it does not update the original value.

So fetching of the random id should be as below

in Page_Load event , give this condition

if (!Page.IsPostBack) {

    randomID = your code;

}


If Not IsPostBack on Page load will solve your problem

[RESOLVED] Disable image rollover button when button is clicked

 

<asp:ImageButton ID="imgRegister" runat="server" onmouseover="~/Images/Buttons/rollover2.jpg"
        onmouseout="~/Images/Buttons/rollover1.jpg" Font-Bold="True" ImageUrl="~/Images/Buttons/rollover1.jpg"
        OnClick="imgRegister_Click" />


Place a label control in the page and the style property display to none (style='display:none;')

Set the some value on click

Check the value before onmouseover and onmouse out

based on that value change the image source (src)



In your current code you had given image path in onmouseover and  onmouseout.That is not correct way because this both is a client side event.

Hence you have to write Javascript function which can change image path and that both function need to put in this both client side event.

 

Please Mark as answer if this is helps

[RESOLVED] ImageButton OnClick cause - Invalid postback or callback argument

I have a page that uses a master page. The following code only shows the bare minimum of the page:


<asp:ListView ID="lvGalleries" runat="server">
  <LayoutTemplate>
    <table>
      <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
    </table>
  </LayoutTemplate>
  <ItemTemplate>
    <tr>
      <td>
        <asp:ImageButton OnClick="LoadGallery_Click" runat="server" ImageUrl='<%# Eval("Url") %>'  />
      </td>
    </tr>
  </ItemTemplate>
  <EmptyDataTemplate>
    <tr><td>none</td></tr>
  </EmptyDataTemplate>
</asp:ListView>




Code-behind:

protected void LoadGallery_Click(object sender, ImageClickEventArgs e) 
    {         
       //code
    }


The

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration 
or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback 
or callback events originate from the server control that originally rendered them.  
If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or 
callback data for validation.




My guess is that it may releated to the ID's that are recreated..

Change the enableEventValidation="true" in the page directive at the top of your aspx page to 'false'

 

You have to add ListView.Databind() in the Page_Load . That will take care of the expression in the imageUrl. Hope this helps

I have DataBind() in the Page_Load.

The change of enableEventValidation="true" to false works.
But the event isnt fires / I dont get to the breakpoint at the beginning of the function. 

And what does enableEventValidation="false" cause?

can you share the code with which you are binding the listview control

Did you saw my previous reply edit?

Its nested code, that execute a select steatment and return datatable. That datatable I bind to the datasource of the listview, then I do databind...

Any thoughts?

are you doing Databinding in IsPostBack Check???? that might be one of the reason for making the event validation corrupted....do databind in all page_load...try like that....

Thanks.

protected void LoadGallery_Click(object sender, ImageClickEventArgs e)
    {
      //code
 }


    protected void Page_Load(object sender, EventArgs e)
    {
        RefreshGalleries();
    }




    private void RefreshGalleries()
    {
        lvGalleries.DataSource = // call to a function that returns datatable
        lvGalleries.DataBind();
    }

this is the code i use

Can you include the code RefreshGalleries(); in If(!IsPostBack) and check what is happening....

I seriously doubt that binding everytime the listview in page_load might cause the problem....

Thanks.

Well, nothing happens. The LoadGallery_Click still isnt firing...

When you click on the link, Does it postback to the server or open the link without a postback?

<div style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #ffffff; margin: 8px;" mce_style="color: #000000; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: #ffffff; margin: 8px;">

I see the page reload - its meen there been a postback, I put breakpoint on the LoadGalleries_Click and it didnt get there.

The ImageButton doesnt have navigateUrl as you can see so theres no link to open.

</div>

I developed a simple example w/ ListView & imageButton ,

just very similar , what you have. This works perfect & I don't see any error.

Here it is

//aspx
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:ListView ID="lvGalleries" runat="server">
  <LayoutTemplate>
    <table>
      <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
    </table>
  </LayoutTemplate>
  <ItemTemplate>
    <tr>
      <td>
        <asp:ImageButton ID="ImageButton1" OnClick="LoadGallery_Click" runat="server" ImageUrl='<%# Eval("URL") %>'  />
      </td>
    </tr>
  </ItemTemplate>
  <EmptyDataTemplate>
    <tr><td>none</td></tr>
  </EmptyDataTemplate>
</asp:ListView>
</asp:Content>




//codebehind
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lvGalleries.DataSource = GetDT();
            lvGalleries.DataBind();
        }
    }


    private DataTable GetDT()
    {
        DataTable dtDFS = new DataTable();
        dtDFS.Columns.Add("ID");
        dtDFS.Columns.Add("URL");
        dtDFS.Columns.Add("Name");


        DataRow dr = dtDFS.NewRow();
        dr["ID"] = 1;
        dr["URL"] = "www.google.com";
        dr["Name"] = "Google";
        dtDFS.Rows.Add(dr);




        dr = dtDFS.NewRow();
        dr["ID"] = 2;
        dr["URL"] = "www.microsoft.com";
        dr["Name"] = "MS";
        dtDFS.Rows.Add(dr);


        dr = dtDFS.NewRow();
        dr["ID"] = 3;
        dr["URL"] = "www.yahoo.com";
        dr["Name"] = "yahoo";
        dtDFS.Rows.Add(dr);
        return dtDFS;
    }
    protected void LoadGallery_Click(object sender, ImageClickEventArgs e)
    {
        int r1 = 9;
    }


 

You got me wonder how this possible, so I dug into my code and saw that all this time i was click the wrong link (this page isnt design yet).

Thanks a lot and sorry for the HUGE mix up.

[RESOLVED] How to activate javascript function from Page_Load and updatepanel

Hi..

In the first Page_Load, I am activating a javascript function to make an ImageButton change between 2 images with an interval.

This works fine.

 

Now when pressing this imagebutton, the Page_Load event will fire the second time and all this is happening in an updatepanel which means a partial postback.

 

The question is how to execute the javascript function stopbk() in the Page_Load event in this scenario as I cant just put it in the "Onload". How can I make that work?

Code is below:

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["SecondLoad"] != null)
        {
            //How to activate stopbk() ?
            Label1.Text = "Second Load";
        }


        if (Session["SecondLoad"] == null)
        {
            Label1.Text = "First Load";
            Session["SecondLoad"] = "dummy";
            body1.Attributes.Add("Onload", "startbk()");
        }
    }
    protected void ImageButton6_Click(object sender, ImageClickEventArgs e)
    {
        //
    }






<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>




<asp:UpdatePanel ID="UpdatePanel4" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<script type="text/javascript">
    var TimerProps = {
        refTimer: null,
        index: 0
    }
    function startTimer() {
        if (TimerProps.index > 1) {
            TimerProps.index = 0;
            document.getElementById('<%= ImageButton6.ClientID %>').src = "http://www.abc.com/images/inboxKuvert.jpg";
            TimerProps.index += 1;
        }
        else {
            document.getElementById('<%= ImageButton6.ClientID %>').src = "http://www.abc.com/images/Transparent.gif";
            TimerProps.index += 1;
        }
    }
    function startbk() {
        TimerProps.refTimer = setInterval("startTimer()", 550)
    }


    function stopbk() {
        clearInterval(TimerProps.refTimer)
    }
</script>


<asp:ImageButton ID="ImageButton6" runat="server" Height="12px" Width="16px"
 ImageUrl="http://www.abc.com/images/inboxKuvert.jpg" onclick="ImageButton6_Click" />


    <br />
    <asp:Label ID="Label1" runat="server" Text="-"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>


 

ASPusers

The question is how to execute the javascript function stopbk() in the Page_Load event in this scenari

ScriptManager.RegisterStartupScript()....

http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerstartupscript.aspx

Thanks.

Thank you,

I have tried to understand the example but are not 100% sure of how the parameters should be set.

My attempt is as below but are not sure if I have done it correctly, I think I miss something?

Example:

RegisterStartupScript( Control control, Type type, string key, string script, bool addScriptTags );

 

My attempt:
RegisterStartupScript(ImageButton6, GetType(), "???", "stopbk()", true); 

It seems to work with the example below:

Thank you!

 

 

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["SecondLoad"] != null)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "stopbk", "stopbk();", true);
            Label1.Text = "Second Load";
        }


        if (Session["SecondLoad"] == null)
        {
            Label1.Text = "First Load";
            Session["SecondLoad"] = "dummy";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "startbk", "startbk();", true);
        }
    }
    protected void ImageButton6_Click(object sender, ImageClickEventArgs e)
    {
        //
    }




<script type="text/javascript">
    var TimerProps = {
        refTimer: null,
        index: 0
    }


    function startTimer() {
        if (TimerProps.index > 1) {
            TimerProps.index = 0;
            document.getElementById('<%= ImageButton6.ClientID %>').src = "http://www.abc.com/images/inboxKuvert.jpg";
            TimerProps.index += 1;
        }
        else {
            document.getElementById('<%= ImageButton6.ClientID %>').src = "http://www.abc.com/images/Transparent.gif";
            TimerProps.index += 1;
        }
    }
    function startbk() {
        TimerProps.refTimer = setInterval("startTimer()", 550)
    }
    function stopbk() {
        clearInterval(TimerProps.refTimer)
    }
    </script>


 

[RESOLVED] Loading a usercontrol into a webpage

Guys: asp.net c# question

I ma trying to load a usercontrol into a table. My usercontrol contains some literal controls.

I can't set the text of these literal controls to anythign, as in my code-behind of my control, whenever I try to access my controls, they come back as null.

My user control code:

<div style="color: Black; background-color: White;" mce_style="color: Black; background-color: White;">
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="OfferControl.ascx.cs"
Inherits="EOwner.Site.French.Controls.OfferControl" %>
<link rel="Stylesheet" href="../styles/OfferControl.css" type="text/css" />
<div id="all" style="background-color: #FFFFF0; height:100%;">
<div id="LeftPanel" style="float: left; width: 65%;">
<div id="title">
<asp:Literal ID="litTitle" runat="server" Text="TitleLabel"></asp:Literal>
</div>
<div id="Blurb">
<asp:Literal ID="litBlurb" runat="server" Text="BlurbLabel" ></asp:Literal>
</div>
<div id="Button">
<asp:ImageButton ID="btnViewOffer" runat="server"
ImageUrl="~/images/ViewOfferButton.jpg" ImageAlign="AbsMiddle" />
</div>
</div>
<div id="RightPanel" style="float: right; width: 35%;">
<div id="address">
<asp:Literal ID="litAddress" runat="server" Text="AddressLabel"></asp:Literal>
</div>
<div id="map">
Map
</div>
</div>
</div>

</div>


and the .cs

<div style="color: Black; background-color: White;" mce_style="color: Black; background-color: White;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EOwner.Contracts.Entities;

namespace EOwner.Site.French.Controls
{
public partial class OfferControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{

}

public Literal lit_Title
{
get { return litTitle; }
set { litTitle = value; }
}

public Literal lit_Blurb
{
get { return litBlurb; }
set { litBlurb = value; }
}

public Literal lit_Address
{
get { return litAddress; }
set { litAddress = value; }
}

public ImageButton btn_ViewOffer
{
get { return btnViewOffer; }
set { btnViewOffer = value; }
}
}
}
</div>



And the code that creates the control

 

 

<div style="color: Black; background-color: White;" mce_style="color: Black; background-color: White;">
foreach (OfferEntity o in offers)
{
OfferControl oc = new OfferControl();
oc.LoadControl("~/Controls/OfferControl.ascx");//GridViewRow gr = new GridViewRow(offers.IndexOf(o), offers.IndexOf(o), DataControlRowType.DataRow, DataControlRowState.Normal);
oc.ID = "oc_" + o.OfferId.ToString();
oc.Attributes.Add("OfferId", o.OfferId.ToString());
oc.lit_Title.Text = o.Title; //Request.QueryString["Title"].ToString();
oc.lit_Blurb.Text = o.Blurb;//Request.QueryString["Blurb"].ToString();
oc.btn_ViewOffer.Attributes.Add("OfferId", o.OfferId.ToString());
//address town postcode
oc.lit_Address.Text = o.Address + Environment.NewLine + o.Town + Environment.NewLine + o.Postcode + Environment.NewLine + o.WebAddress;

TableRow tr = new TableRow();
TableCell tc = new TableCell();
//pass in offer id, list is stored in the session, use the id in the usercontrol to get the data

tc.Controls.Add(oc);
tr.Cells.Add(tc);
tOffers.Rows.Add(tr);

//tbl.Rows.AddAt(gvOrderDetail.Rows.Count + 1, row);
}
</div>

 

Despite having the get/sets for every control, I can't seem to set the values of the controls, keep getting a nullreferenceexception. Even if I try to set the values of the controls in the usercontrol itself, I still can't access the controls.

Any pointers?


Andrew Berry - Software analyst/Developer