Category Archives: PlaceHolder

[RESOLVED] Eval(Session("session_variable"))

Can I Eval a session variable in WebForms? 

Check out this example:

ASPX

<%@ page language="C#" masterpagefile="~/MasterPages/Default.master" autoeventwireup="true"
	codefile="CallAMethodInline.aspx.cs" inherits="HowTo_CallAMethodInline"
	title="How To: Call A Method Inline" %>

<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server">
	<div>
		Static Method: <%= MathHelper.Add(2, 2) %>
	</div>
    <div>
        Protected Method: <%= Add(2, 2) %>
    </div>
    <div>
        Protected Property: <%= Result %>
    </div>
    <div>
        Session Object: <%= Session["Result"] %>
    </div>
</asp:content>



CODE-BEHIND

using System;

public partial class HowTo_CallAMethodInline : System.Web.UI.Page
{
    protected int Result;

    protected void Page_Load(object sender, EventArgs e)
    {
        Result = this.Add(2, 2);
        Session["Result"] = this.Add(2, 2);
    }

    protected int Add(int x, int y)
    {
        return x + y;
    }
}



Okay, that worked, thanks for the great example. BUT, can you not use the same approach to a <asp:TextBox or <asp:Label using Eval or Bind, i.e;

<asp:TextBox id="txt_userId" runat="server" Text='<%# Eval("Session(""USERID"")") %>' 

Thank you!

To the best of my knowledge, you can't do that, unless someone else knows of a way.

[RESOLVED] onclientClick before OnServerClick

hi,

 i would like to do the validation work using javascript or jquery in onclientclick and then show blockUI , next page using server click.

but, i have a captcha validation in server click and i do'nt know how to validate the captcha in jquery or javascript.

    protected void btnRegister_Click(object sender, EventArgs e)
    {        
        lblMessage.Text = "";
        if (Page.IsValid)
        {
            if (txtUserName.Text == "")
            {
                lblMessage.Text = "نام کاربری را وارد نمائید";
                txtUserName.Focus();
                return;
            }
            if (!BLL.IsStrictPassword(txtPassword.Text))
            {
                lblMessage.Text = "طول کلمه عبور حداقل باید 5 کاراکتر باشد";
                txtPassword.Focus();
                return;
            }
            if (ddlYear.Text == "<سال>" || ddlMonth.Text == "<ماه>" || ddlDay.Text == "<روز>")
            {
                lblMessage.Text = "لطفا تاریخ تولدتان را وارد نمائید";
                return;
            }
            if (!chk_Low.Checked)
            {
                lblMessage.Text = "برای عضویت می بایست قوانین سایت را بپذیرید";
                return;
            }
            if (txtSecurityCode.Text == String.Empty)
            {
                lblMessage.Text = "کد امنیتی را وارد نکرده اید";
                txtSecurityCode.Focus();
                return;
            }
            secCode.ValidateCaptcha(txtSecurityCode.Text);
            if (!secCode.UserValidated)
            {
                lblMessage.Text = "کد امنیتی نادرست وارد شده است";
                return;
            }
            try
            {
//some code
}
}

I don't know the answer, but why don't you use the ASP.NET validation controls? They run on the client and will handle much of this for you.

At the end of your client validation function defined in the button's "onclientclick" attribute either return true (validation success, go on with the postback) or false (validation not successful, halt all other javascript functions)

actually if you use the asp.net validation controls you will be using JavaScript automatically because they will generate javascript validation code and insert it to your pages html code at runtime.

hi

thanks for all replys.

but my main problem is captcha validation.as i said before,i have a piece code in server click that validate the captcha.

i use the asp.net validation for other controls in the page,but what i do for captcha, or how to communicate between client and server click.

thanks a lot


[RESOLVED] How to access content page controls from master page in asp.net

it is very easy to access master page control from content page like

    protected void Page_Load(object sender, EventArgs e)
    {
        // content page load event
        DropDownList thisDropDown = this.Master.FindControl("someDropDown") as DropDownList;
        userLabel.Text = thisDropDown.SelectedValue;
    }

but how could i access controls of content page from master page. suppose a textbox there in content page and one button is there in master page. i want that when i will click on master page button then i want to show the text of textbox in the content page in the label of master page. how to achieve it. please help me with code sample. thanks.

you need to call FindControl from the contentplaceholder in the masterpage

this.ContentPlaceholder1.FindControl("SomeControlOnContentPage")

keep in mind that since many content pages can use that masterpage, they might not all have the control you are looking for.  so be sure to check the FindControl result for null before you try to do anything else with it.

[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] dynamically add checkboxes to a calendar control...

I want to add two checkboxes to selected days in a calendar control.  I can do that but I can not figure out how to get the checkboxes to fire an event.   I tried to get a button to fire and event by iterating through the panel without success either. Here is my code so far:

Thanks in advance,

Photon (Springfield, Missouri)

 

<%@ Page Title="" Language="VB" MasterPageFile="~/Default.master" AutoEventWireup="false" CodeFile="Caledar_Add.aspx.vb" Inherits="Admin_Caledar_Add" %>

<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
    
    <div id="home">
     <div id="Div" runat="server" style="width: 810px; height: 500px;">
   <div id="sidebar">
       
               
                 <asp:Button ID="Button_GetCheckBox" runat="server" Text="Button" />
                 <asp:Label id="Label1" runat="server" />
             </div>
       
             <asp:Panel ID="Panel1" runat="server">
           
       
       
      <div id="content">
          <h3><font face="Verdana">Adding Custom Content to Calendar</font></h3>
          <asp:Calendar id="Calendar1" runat="server"
                    ondayrender="Calendar1_DayRender"
                    onselectionchanged="Date_Selected"
                    ShowGridLines="true"
                    BorderWidth="1"
                    Font-Names="Verdana"
                    Font-Size="9px"
                    Width="500px"
                    VisibleDate="01/01/2011"
                    TitleStyle-BackColor="Red"
                    TitleStyle-Font-Size="12px"
                    TitleStyle-Font-Bold="true"
                     DayStyle-VerticalAlign="Top"
                    DayStyle-Height="50px"
                    DayStyle-Width="14%"
                    SelectedDate="1/1/0001"
                    SelectedDayStyle-BackColor="Red" />
                </asp:Panel>
  
  </div>
  </div>
  </div>

</asp:Content>

 

'**Code Behind**
Partial Class Admin_Caledar_Add

    Inherits System.Web.UI.Page

    Dim holidays(12, 31) As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        holidays(1, 1) = "New Year's Day"
        holidays(1, 26) = "Australia Day"
        holidays(2, 2) = "Groundhog Day"
        holidays(2, 14) = "Valentine's Day"
        holidays(3, 17) = "St. Patrick's Day"
        holidays(4, 1) = "April Fool's Day"
        holidays(5, 1) = "May Day"
        holidays(6, 15) = "My Birthday"
        holidays(7, 15) = "My Anniversary"
        holidays(8, 15) = "My Mother's Birthday"
        holidays(9, 24) = "Autumnal Equinox"
        holidays(12, 26) = "Boxing Day"

    End Sub
   

    Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As DayRenderEventArgs)

        Dim d As CalendarDay
        Dim c As TableCell

        d = e.Day
        c = e.Cell

        If d.IsOtherMonth Then
            c.Controls.Clear()
        Else
            Try
                Dim Hol As String = holidays(d.Date.Month, d.Date.Day)
                'Response.Write(Hol)
                If Hol <> "" Then
                   
                    Dim _checkbox_Delete As CheckBox = New CheckBox()
                    _checkbox_Delete.ID = "chkDynamicCheckBox_Delete"
                    _checkbox_Delete.Text = "Delete"
                    c.Controls.Add(New LiteralControl("<br>" + Hol.ToString + "<br/>"))
                    c.Controls.Add((_checkbox_Delete))
                   
                    AddHandler _checkbox_Delete.CheckedChanged, AddressOf _checkbox_Delete_CheckedChanged
                End If
            Catch exc As Exception
               
                Response.Write(exc.ToString())
            End Try
        End If
    End Sub

   


   

    Function _checkbox_Delete_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim objCheckbox = DirectCast(sender, CheckBox)
        Response.Write("test")
    End Function

   

    Protected Sub Button_GetCheckBox_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button_GetCheckBox.Click
        For Each ctl As Control In Panel1.Controls
    
            If TypeOf ctl Is CheckBox Then
                'CType(ctl,CheckBox).ID
                Response.Write("test")
            End If
        Next ctl

    End Sub


End Class

 

I haven't got a response  so I will try again in a more focused way.  I have created a calendar control using ASP.net visual studio express 2008.  In the dayrender event, I have dynamically created  checkboxes.  My problem is I am not able to fire an event through an event handler.  What am I not doing correctly?  Below is my code:

Thanks in advance,

Photon

 

<%@ Page Title="" Language="VB" MasterPageFile="~/Default.master" AutoEventWireup="false" CodeFile="testcalendar.aspx.vb" Inherits="Admin_testcalendar" %>

<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
    <div id="content">
         
  <h3><font face="Verdana">Adding Custom Content to Calendar</font></h3>

    <asp:Calendar id="Calendar1" runat="server"
                    ondayrender="Calendar1_DayRender"
                    ShowGridLines="true"
                    BorderWidth="1"
                    Font-Names="Verdana"
                    Font-Size="9px"
                    Width="500px"
                    VisibleDate="01/01/2011"
                    TitleStyle-BackColor="Red"
                    TitleStyle-Font-Size="12px"
                    TitleStyle-Font-Bold="true"
                     DayStyle-VerticalAlign="Top"
                    DayStyle-Height="50px"
                    DayStyle-Width="14%"
                    SelectedDate="1/1/0001"
                    SelectedDayStyle-BackColor="Red" />
                   
    </div>

</asp:Content>

'***Code Behind****

Partial Class Admin_testcalendar
    Inherits System.Web.UI.Page

    Protected Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender
       
        e.Cell.Text = ""
        Dim c As New CheckBox()
        c.Text = e.Day.DayNumberText
        AddHandler c.CheckedChanged, AddressOf _checkbox_CheckedChanged
        c.AutoPostBack = True

        e.Cell.Controls.Add(c)

    End Sub

    Protected Sub _checkbox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim objCheckbox = DirectCast(sender, CheckBox)

        'this response.write does not fire when a checkbox is checked
        Response.Write("test")
    End Sub
End Class


 

 

 

 

Hi,

Photon

I have dynamically created  checkboxes.  My problem is I am not able to fire an event through an event handler.  What am I not doing correctly
 

When we dynamically add control in page. We should notice that in page_Init as well as page_load is the best period for us to add control.

Calendar1_DayRender evnet is a very later event in page life cycle. So "AddHandler c.CheckedChanged, AddressOf _checkbox_CheckedChanged" will not trigger the event.

Alternative way is to use Page.ClientScript.GetPostBackEventReference to add a postback event manually to checkbox.

Like:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["__EVENTTARGET"] != null)
            {
                Response.Write(Request.Form["__EVENTARGUMENT"]);
            }
        }


  protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
        {
            e.Cell.Text = "";
            CheckBox cb = new CheckBox();
            cb.ID = "cb_" + e.Day.Date.ToString();
            cb.Text = e.Day.DayNumberText;
            cb.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(cb, "CheckChanged");  //add postback event(javascript)
           

            e.Cell.Controls.Add(cb);
        }


And also the calendar can not remain the checkbox checked state on postback, so you need to use some state management object to store the checkbox checked list and remain them manually.

Hope this can help you.