Tag Archives: PlaceHolder

[RESOLVED] A potentially dangerous Request.Form value was detected from the client ...

Hi there 


I am creating a small CMS, I have a page with an HTML editor. the user enters text, submit, this of course populates a sqlServer database. 

When I submit the form, I get the following error:

a potentially dangerous Request.Form value was detected from the client (ctl00$ContentPlaceHolder1$elm2="<p>Test</p>").

I tried different things:

- I added ValidateRequest="false" on the top of the page

- In the code behind which deals with the Insert to DB, my Insert parameter is as follow:

commI.Parameters.Add("@body", SqlDbType.Text);

commI.Parameters["@body"].Value = HttpUtility.HtmlEncode(elm2.Text);

None of the above have fixed it

Christophe



Hi,

Yes it is due to .net framework 4.0....

solution is put below tag under <system.web>.......


<system.web>

<httpRuntime requestValidationMode="2.0" ></httpRuntime>

</system.web>

add validateRequest="false" in your page directive and check it


If you just want to fix the error you can add the following to your .config file which will allow the ValidateRequest="false" directive to take effect with .net v4

<system.web>

<httpRuntime requestValidationMode="2.0"/>    

</system.web>

I am pretty sure thats all that needs to be done

Add

enableEventValidation="false" viewStateEncryptionMode="Never" enableViewStateMac="false"

in the Page directive


On page directive set ValidateRequest="false" and your error will be solved......

You can try ClientScript.RegisterForEventValidation function & keep EventValidation ON.

http://msdn.microsoft.com/en-us/library/ms366515.aspx

http://msdn.microsoft.com/en-us/library/ms223395.aspx

If this doesn't help, please post your code. 

Thanks for that, that nailed it.


Christophe

Adding a PayPal button within content detail of MasterPages

How do you add a  PayPal button inside of a content detail of a master page.  Since a MasterPage automatically encapsulates and nests ALL of the code of its contentplaceholder, by definition...all design and coding in a contentplaceholder cannot encorporate a form.  This is true because w3 specs do not allow the nesting for forms.

 

Simple MasterPage
'  No form can exist in the rest of this page...because you cannot nest forms within forms.  Since ASP.NET is about to require the detail page to be within an asp.net form, it does not straightforwardly support any sequential forms in the detail page that follows


<form id="form1" runat="server">
	<asp:ContentPlaceHolder runat="server" id="ContentPlaceHolder2">
	Header  ' NO FORMS can go in HERE
	</asp:ContentPlaceHolder>


<asp:ContentPlaceHolder runat="server" id="ContentPlaceHolder1">
Main Content ' NO FORMS can go in HERE
</asp:ContentPlaceHolder>
</form>


'I could put a sequential form here...but this is the end of the webpage and back in the Master Page....nothing really left to do.


 

hi,

Can you place the PayPal butto before the ContentPlaceHolder or form1. We can have multiple forms on the page as long as only one of them has the runat="server" attribute.

No..

The entire purpose of a master detail page is such that the Master page contains the basic "frames (content)" layout.  ALL of the primary web content is in a contentplaceholder.  I don't see that as atypical.  99.9999% of all master/detail pages are arranged in this fashion.   

And a PayPal button is the tip of the iceburg.  There are literally thousands of normal cross-post applications in any normal web application out there where a form must reside within a content place holder. 

Hi,

According to your description ,I would like to suggest you to check the link below for the article which describes about how to include multiple form tags in an ASP.NET page.

http://www.codeproject.com/Articles/36071/Implementing-Non-ASP-NET-Posts-in-ASP-NET.aspx

Hope it can help you.

Thanks, unfortunately rewriting the worlds software code just so it will work with Microsoft is "RARELY" an option.   The problem with this rewrite is now it will ONLY will asp.net...it won't stand-alone anymore and work on its own.

[RESOLVED] Using REQUEST("ListBoxName") to get values

So I have a master page and inside it is a content place holder. In that content place holder is a panel with a bunch of multi select list boxes. Under that panel is a button.

when I click the button, I want to use the REQUEST object to get a comma separated string of my list box selected values. It does not seem to create a string though.. I have done this before on just plain Webforms without a master page and it worked fine. Could you help explain what I am doing wrong??

This is a section of my code:


Protected Sub FilterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        

        'Strings to store comma separated selections
        Dim MethodIDSelection As String
        MethodIDSelection = Request.QueryString("MethodNameLB")
                

        If MethodIDSelection = "" Then
            Label5.Text = "Method was blank"
        Else
            Label5.Text = MethodIDSelection
        End If
        

    End Sub


According to your wording above the button is on the Content Page with the ListBoxes.  Are you passing the query string to this page and you simply want to pre-select the items in the list boxes or you want to generate a query string from the selections to pass to another page?

If you are trying to generate a comma separated list can we see the code you used to create the ListBoxes?  If it is data driven then be sure you are reloading the data after the postback.  I also do not see any code to even loop through the listboxes and create a list.  I do recommend StringBuilder instead of String with a simple += because it is more efficient.

Sudo Code:

Dim MyString As New StringBuilder


For Each Item As ListItem In MyListBox
     If Item.Selected Then
          MyString.Append("," & Item.Text)
     End If
Next


Response.Redirect("NewPage.aspx?selected=" & MyString.ToString, False)

If you are trying to read the query string the above code should be in the Me.Load method handler.  Once the button is clicked it initiates a postback and will most likely loose the query string.

Sorry page lost formatting so I deleted it.

Sorry, I guess I missed out some information. I didn't mean to use the .QueryString. Just use Request("MethodNameLB"). Also, the data in the listbox is from an object datasource attached to a database. Here is the code for the entire ASPX page. Its pretty straightforward.


<%@ Page Title="" Language="VB" MasterPageFile="~/SuperPage.master" %>


<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>


<script runat="server">
    

    Protected Sub FilterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)


        'Strings to store comma separated selections
        Dim MethodIDSelection As String
        MethodIDSelection = Request("MethodNameLB")
                

        If MethodIDSelection = "" Then
            MyLabel.Text = "Method was blank"
        Else
            MyLabel.Text = MethodIDSelection
        End If
        

    End Sub
    

</script>


<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="TitleContent" Runat="Server">
Test Page</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">


<div style="font-family: Verdana; font-size: small">
   

    <asp:ObjectDataSource ID="PersonalMethodsData" runat="server"
            OldValuesParameterFormatString="original_{0}" SelectMethod="GetPersonalMethodsDataByActive"
            TypeName="PersonalMethodsBLL"></asp:ObjectDataSource>
            





    <asp:ListBox ID="MethodNameLB" runat="server" DataSourceID="PersonalMethodsData"
                            DataTextField="MethodName" DataValueField="PersonalMethodID"
                            SelectionMode="Multiple"></asp:ListBox>
    <cc1:ListSearchExtender ID="MethodNameLB_ListSearchExtender" runat="server" PromptCssClass="searchExtender"
                            PromptPosition="Bottom" PromptText=""
    TargetControlID="MethodNameLB">
    </cc1:ListSearchExtender>
    <br />
    <asp:Label ID="MyLabel" runat="server" Text="Label"></asp:Label>
<asp:Panel ID="InputPanel" runat="server">
</asp:Panel>
<asp:Button ID="FilterButton" runat="server" Text="Filter View" onclick="FilterButton_Click" />


</div>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ScriptHolder" Runat="Server"></asp:Content>


Using just Request(key) is not nearly as efficient as specifying the actual source.  The Request(key) command will look through the Request.Forms, Request.QueryString, Request.Cookies, and Request.ServerVariables just to find a match.  If you want the application to create a comma separate list I would suggest using a session variable to maintain the data and not the Request object.  You should use a ViewState if you only need the data on that page.  To create the list though you don't need to assign the object to anything until the end.

Now I am not too familiar with ObjectDataSource controls but I do know for the selected items to remain you need to reload the data on postback from the previous source and not reload the data each time from the database.  If you load it each time it will clear the checked items before it ever runs the button click event.  I always load data in a BindData method similar to the code below.  It allows for easier debugging and less web code.  Hope this helps point you in a different direction that works.

Dim myData As DataTable


Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
     If Not IsPostBack Then
          BindData(True)
     Else
          myData = CType(ViewState("TableData"), DataTable)
     End If
End Sub


Private Sub BindData(Optional ByVal RefreshData As Boolean = False)
     If RefreshData Then
          myData = GetPersonalMethodsDataByActive()
          ViewState("TableData") = myData
     End If


     MethodNameLB.DataSource = myData
     MethodNameLB.DataBind()
End Sub


Protected Sub btnFilter_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFilter.Click
     Dim MyList As New StringBuilder
     For Each Item As ListItem In MethodNameLB
          If Item.Selected Then
               MyList.Append("," & Item.Value)
          End If
     Next
     If MyList.Length > 0 Then MyList.Remove(0, 1)
     Session("SelectedItems") = MyList.ToString
End Sub


 

This can be done without using Request object. Here's an example, which you may write in codebehind of your content page.


string strTemp1 = "";
foreach (ListItem item in ListBox1.Items)
{
     if (item.Selected == true)
     {
               
        strTemp1 += (strTemp1 == "") ? item.Value : "," + item.Value;
      }

I just figured using the request object would be easiest. But it doesn't seem to work if the listbox in inside of an update panel. My guess is because their is only a partial page postback and the request() never gets called.

My main goal is to try and simplify the code. I don't like the looping through method as it is messy and I have to due this on several list boxes. I have resorted to LINQ as an alternative but have ran into another problem I'm hoping someone can help me out with. I can use LINQ to get the either the .text of the list box items or the .value, but I don't know how to get both at the one time and return them into an array.

Anyhow this is what I have moved toward:

Dim TextString As String = ""
Dim ValueString As String = ""


Dim selItemsText = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select li.Text


Dim selItemsValue = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select li.Value


TextString = Join(selItemsText.ToArray, ",")
ValueString = Join(selItemsValue.ToArray, ",")


'I would like to do this using 1 LINQ statement selecting separate entities like this:


Dim TextString As String = ""
Dim ValueString As String = ""


Dim selItems = From li As ListItem In ChooseSampleType.Items _
Where li.Selected Select New With {.itemtext = li.Text, .itemVal = li.Value}


TextString = Join(selItems.itemtext.ToArray, ",")
ValueString = Join(selItems.itemVal.ToArray, ",")


I'm not sure if this is possible or not, or if my code is even accurate as I haven't tested it, but this is what I'm trying to accomplish. So if I had a listbox with the following data I would get the following strings:

listboxText - listboxValue - Selected

A - 1 - YES

B - 2 - NO

C - 3 - YES


TextString = "A,C"

ValueString = "1,3"




Note: I am using VB.net not C# or old versions of VB so an answer in VB.Net would be much appreciated. Thanks

Hi,

Hybird

I want to use the REQUEST object to get a comma separated string of my list box selected values. It does not seem to create a string though.. I have done this before on just plain Webforms without a master page and it worked fine.
 

According to your description ,for my experience the Request object can retrieve the values that the client browser passed to the server during an HTTP request.

As far as I know you can use Request["nameOfControl"] to get control's value. 

However ,if you use a master page ,the name of control(which is contained in the content page) is not the same as its'ID.

Thus,the code which as you mentioned in your post :Request("MethodNameLB") can not get the value.

I would like to suggest you to check the sample below which shows how to use Request object to get the value of the control which is contained in content page.

1.Code in master page(.master):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>


2.Code in content page(.aspx):

 

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language="javascript" type="text/javascript">
    function GetNameOfListBox() {
        var listbox = document.getElementById("<%=ListBox1.ClientID %>");
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        hidden.value = listbox.name;
    }
</script>
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <asp:HiddenField ID="HiddenField1" runat="server" />
</asp:Content>


 

3.Code in content page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.Page.ClientScript.RegisterStartupScript(Me.[GetType](), "Ming", "GetNameOfListBox()", True)
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim listboxName As String = Me.HiddenField1.Value
        If Request(listboxName) IsNot Nothing Then
            Response.Write(Request(listboxName).ToString())
        End If
    End Sub


 

 

Hybird

But it doesn't seem to work if the listbox in inside of an update panel.

Please just modify the code(in content page) which I mentioned above:

1.Code in content page(.aspx):

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
    function GetNameOfListBox() {
        var listbox = document.getElementById("<%=ListBox1.ClientID %>");
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        hidden.value = listbox.name;
    }
</script>
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <asp:HiddenField ID="HiddenField1" runat="server" />
    </ContentTemplate>
    </asp:UpdatePanel>

</asp:Content>


 

2.Code in content page(.vb):

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Me.Page.ClientScript.RegisterStartupScript(Me.[GetType](), "Ming", "GetNameOfListBox()", True)
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim listboxName As String = Me.HiddenField1.Value
        If Request(listboxName) IsNot Nothing Then
            'Show Result.
            Me.Label1.Text = Request(listboxName).ToString()
        End If
    End Sub


 

Hybird

I can use LINQ to get the either the .text of the list box items or the .value, but I don't know how to get both at the one time and return them into an array.

You can create an Entity class and pass the entity to an array as below:

Create a new page to demo the sample:

1.Code in page(.aspx):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"></asp:ListBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


2.Code in page(.vb):

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Bind()
        End If
    End Sub
    Public Sub Bind()
        Me.ListBox1.DataSource = Get_source()
        Me.ListBox1.DataTextField = "CountryName"
        Me.ListBox1.DataValueField = "CountryID"
        Me.ListBox1.DataBind()
    End Sub
    ' You can get the data from your own database.
    ' I get the value like this in order to make the page convenient to run and read.
    Public Function Get_source() As DataTable
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim CountryNames As String = "Country1,Country2,Country3,Country4"
        Dim CountryIDs As String = "1,2,3,4"
        Dim list1 As String() = CountryNames.Split(","c)
        Dim list2 As String() = CountryIDs.Split(","c)
        dt.Columns.Add(New DataColumn("CountryName"))
        dt.Columns.Add(New DataColumn("CountryID"))
        For i As Integer = 0 To list1.Length - 1
            dr = dt.NewRow()
            dr("CountryName") = list1(i)
            dr("CountryID") = list2(i)
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
    Public list As New List(Of Items)()
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        For Each item As ListItem In Me.ListBox1.Items
            If item.Selected Then
                Dim i As New Items()
                i.ID = item.Value
                i.Text = item.Text
                list.Add(i)
            End If
        Next

        ' Now you can the value like this:
        For Each listitem As Items In list
            Response.Write(("Text:" + listitem.Text & " value:") + listitem.ID & "<br/>")
        Next
    End Sub


End Class

' Entity Class 
Public Class Items
    Private _id As String
    Private _text As String

    Public Property ID() As String
        Get
            Return _id
        End Get
        Set(ByVal value As String)
            _id = value
        End Set
    End Property
    Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property
End Class


Hope it can help you.

Wow, thank you Ming, that was an extremely informative post! Thanks for taking the time to actually create the test pages!

A note on some things I had to modify to get it working in case other people happen to stubble upon this informative post:

1.) in order to use the type datatable, at the top of your master page or content page you must include

<%@ Import Namespace="System.Data" %>

2.) I have a separate script content place holder where I generally place all of my scripts, and If I placed the

<script language="javascript" type="text/javascript">
          function GetNameOfListBox() {
              var listbox = document.getElementById("<%=ListBox1.ClientID %>");
              var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
              hidden.value = listbox.name;
          }  
 </script>

section of code in there it would not work. I had to place it in the same content place holder as the one where the hidden field is located.


Thanks again for your solution! Works wonders.

[RESOLVED] FindControl method doesn't work with masterpage

Hi all, i have a masterpage and other pages. i want to use findcontrol method to find a textbox (not on the master page) to check whether it is empty or not.

my code is as folows;

Dim myContentPlaceHolder As ContentPlaceHolder = CType(Master.FindControl("MainContent"), ContentPlaceHolder)

Dim UpdatePanel1 As UpdatePanel = CType(myContentPlaceHolder.FindControl("UP1"), UpdatePanel)

Any help please. 

 

Dim tmptxt As TextBox = CType(Master.FindControl("txtbox1"), TextBox)


If Not tmptxt Is Nothing Then
 'get tmptxt.Text value
End If


my textbox in not on the masterpage, it is on the default.aspx page. i tried

Dim myTextBox As TextBox = CType(Master.FindControl("TextBox1"), TextBox)  , but doesn't worked. Any more help please

i should also mention that the TextBox1 is inside listview, the listview is inside an updatepanel (updatepanel is inside a panel -ajax modalpopupextender).

Hi,

First you need to find the textbox in listview. Since I'm not sure which textbox you find in listview. Here's a example:

<asp:ListView ID="ListView1" runat="server">
            <ItemTemplate>
                <tr id="Tr2" runat="server">
                    <td align="center">
                        <asp:Label ID="lbP1" runat="Server" Text='<%#Eval("P1") %>' />
                    </td>
                    <td align="center">
                        <asp:Label ID="lbP2" runat="Server" Text='<%#Eval("P2") %>' />
                    </td>
                   

                </tr>
            </ItemTemplate>
</asp:ListView>
Protected Sub FindItems()
	Dim ctl As Control = Me.ListView1.Items(0).FindControl("lbP1")  //find textbox in the first item of ListView
End Sub

Protected Sub Button1_Click(sender As Object, e As EventArgs)
	FindItem()
End Sub


Find the child page's ListView in masterpage:

Dim panel As UpdatePanel = TryCast(Me.ContentPlaceHolder1.FindControl("UpdatePanelID"), UpdatePanel)
Dim listview As ListView = TryCast(panel.FindControl("ListViewID"), ListView)


Please notice that if the control is wrapped in a parent control, you need to first find the control from this parent control(container).

Here are some good article:

http://weblogs.asp.net/dwahlin/archive/2006/08/25/Finding-ASP.NET-Child-Controls_2E002E002E002E00_The-Simple-Way.aspx

http://www.west-wind.com/Weblog/posts/5127.aspx

Hope this can help you.
 

[RESOLVED] creating hyperlinks dynamically.

I want to create hyperlink dynamically whenever i click the button below is my code

int j = 1;
        for (int i = 0; i < j; j++)
        {
            //HyperLink links = new HyperLink();
            HyperLink hplink = new HyperLink();
            hplink.NavigateUrl = "http://www.asp.net";
            hplink.Text = "Click Here" + "<br /><br />";
            ph.Controls.Add(hplink);
        }

but i am unable to get the hyperlinks dynamically because the loop is going infinite.

for (int i = 0; i < j; j++) 


--> for (int i = 0; i < j; i++) 


Replace j++ with i++, since i is your looping variable. 

Ya when i have done what you have said but i am getting only one hyperlink when i press the button,i want to createhyperlinks whenever i click the button, i mean how many times i click the button that many times i have to get hyperlink. 

Here is a way to do that


1;) in your aspx markup :

<body>
    <form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <br />
    <asp:Literal runat="server" ID="LinksPlaceHolder" />
    </form>
</body>


2;) in the code-behind :

    protected void Button1_Click(object sender, EventArgs e)
        {
            LinksPlaceHolder.Text += "<a href=\"http://www.asp.net/\">go to the asp.net website</a><br/></br>";
        }


if this  is not what you want, explain exactly what your are trying to do


This video shows one way of doing something like that: http://www.asp.net/ajax/videos/how-to-dynamically-add-controls-to-a-web-page 

There is a major problem with creating a new hyperlink each time a button is pressed.  Dynamic controls have to be redrawn each time the page loads.  In order to redraw a different hyperlink each time a button is pressed you will need to have a lists of hyperlinks in a DataTable or HybridDictionary that create the hyperlinks each time the button click causes a postback.  Your redraw loop is close but it should use a For Each and loop through the collection of hyperlink data and draw a control for each one during the Page Init method.  In the button click simply add the new hyperlink data to the collection.  Dynamic controls are pain and should be avoided whenever possible. 

Are you saying about tables rows and columns and adding the control to column and generating whenever the button is clicked?? but i want to achieve with a for loop is it possible?? 

For example the DataTable would contain columns CONTROL_ID, URL, TEXT.  Each time the button is clicked you create a new row from the DataTable fill in the fields and add the row to the data and store it in the ViewState.  Each time the page load you read the DataTable with your for each Row loop and add your hyperlinks to the placeholder.  This will make sure the drawing is constant each time and you only have to debug the data is getting updated and added properly.   

I think a little bit of code can explain much than big sentences.

Invalid loop for (int i = 0; i < j; j++)  

Write loop 

>> for (int i = 0; i < j; i++)  

Hi,

Http is stateless, Dynamically created control can not maintain itself after postback.

If you dynamically add a HyperLink Control to the page during button click, be aware that every PostBack is a new Request .They need to be recreated each time the page loads.

Check this two links, they give you some example and explanation:

http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Studio_.NET_2005/Q_23207581.html

http://forums.asp.net/t/1186195.aspx

Hope this can help you.

Here you have increamented j++, that should be i++. so in your case conditon not get false at any time so that is goes in infinate looks

change as per below code

int j = 1;
        for (int i = 0; i < j; i++)
        {
            //HyperLink links = new HyperLink();
            HyperLink hplink = new HyperLink();
            hplink.NavigateUrl = "http://www.asp.net";
            hplink.Text = "Click Here" + "<br /><br />";
            ph.Controls.Add(hplink);
        }


 

Please mark as answer if this is helps