Create new account I forgot my password    

Create a Table Dynamically in ASP.NET 2.0 and ASP.NET 3.5
Rating: 112 user(s) have rated this article Average rating: 4.4
Posted by: Suprotim Agarwal, on 4/2/2008, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 124403 times
Abstract: In this article, we will see how to create a table dynamically in asp.net. We will accept the number of rows and columns in the table from the user. We will then use the Page_Load() event to create the table dynamically and to save the state of the table on each postback.

Create a Table Dynamically in ASP.NET 2.0 and ASP.NET 3.5
 
I had recently received a request from a dotnetcurry.com visitor about creating a dynamic table in ASP.NET. Now there are plenty of solutions available on the net. Most of the solutions I found, advised creating a dynamic table in the Page_Init() event, since the values of controls already exist in this event and can be used after a postback occurs. However this solution works best when the number of rows and columns are fixed, and then the table is created. But what if the number of rows and columns to be created, are to be accepted from the user, at runtime? In this article, we will explore how to accept the number of rows and columns from the user, create the table in the Page_Load() event and also retain the values on postback.
Whenever a control is added to the page dynamically, it is not persisted by default. That is because these ‘dynamically’ added controls are not automatically added to the page view state. Remember that for a dynamic control, the viewstate is available only after the post back occurs.
To elaborate on the above statement, the page is recreated each time it is posted back to the server. In other words, a new instance of the Page class is created and the class variables are set using the values from the ViewState. However during this recreation, the dynamically created controls are no longer available and hence the values are lost in the viewstate.
To override this behavior, you need to somehow make these controls available on each postback. One way of doing so, is to override the LoadViewState() method of the page. In the LoadViewState(), the view state data that had been saved from the previous page visit is loaded and recursively populated into the control hierarchy of the Page.
Why the LoadViewState()?
When the controls are added to page, it is done quiet early in the page event cycle. Hence the LoadViewState() gives you an ideal placeholder to recreate the controls. Since the LoadViewState() method is called before the Page_Load() event, re-adding controls in this method assures that the controls can be access and manipulated by the time any event occurs on them.
Why have you chosen to create and recreate the controls on Page_Load() instead of Page_Init()?
You can create dynamic controls in either the Page_Init() or Page_Load().
However as already explained in the introduction, we would be accepting the rows and columns from the user to create the table. Since these values would be available only after the user has entered the values in the two textboxes and clicked the button to cause a postback, the best suitable place is the Page_Load().
The second reason of choosing Page_Load() over Page_Init() is that in this example, we will be setting a flag on the ViewState to determine if the dynamic table has to be recreated or not. ViewState values are available during the Page_Load() and ‘not’ during the Page_Init() event.
Let us see some code now.
Step 1: Create a new ASP.NET application. Add two textboxes (txtRows and txtCols) and a button (btnGenerate) control to the page. The two textboxes will accept the number of Rows and Columns from the user. Based on the input in the textboxes, the table will be created dynamically on the button click. Also add a container element (to position the table) and a button (btnPost) to cause a postback the second time, once the table data is manipulated.
The mark up will look similar to the following:
<body>
    <form id="form1" runat="server">
    <div>
    <div>
        Rows: <asp:TextBox ID="txtRows" runat="server" Width="30px"> </asp:TextBox> <br />
        Cols: &nbsp;<asp:TextBox ID="txtCols" runat="server" Width="30px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="btnGenerate" OnClick="btnGenerate_Click" runat="server" Text="Generate" />&nbsp;<br /> <br />
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <br />
        <br />
    </div>
    </div>
        <asp:Button ID="btnPost" runat="server" OnClick="Button1_Click" Text="Cause Postback" />
    </form>
</body>
 
Step 2: The number of rows and columns for the table is to be taken from the user. For this purpose, we will accept the values in the Page_Load() event. We will create properties for both the rows and columns and store in the ViewState so that the data is available on the postback.
C#
// Rows property to hold the Rows in the ViewState
    protected int Rows
    {
        get
        {
            return ViewState["Rows"] != null ? (int)ViewState["Rows"] : 0;
        }
        set
        {
            ViewState["Rows"] = value;
        }
    }
 
    // Columns property to hold the Columns in the ViewState
    protected int Columns
    {
        get
        {
          return ViewState["Columns"] != null ? (int)ViewState["Columns"] : 0;
        }
        set
        {
            ViewState["Columns"] = value;
        }
    }
protected void Page_Load(object sender, EventArgs e)
    {
        // Run only once a postback has occured
        if (Page.IsPostBack)
        {
            //Set the Rows and Columns property with the value
            //entered by the user in the respective textboxes
            this.Rows = Int32.Parse(txtRows.Text);
            this.Columns = Int32.Parse(txtCols.Text);
        }
 
        CreateDynamicTable();
    }
VB.NET
' Rows property to hold the Rows in the ViewState
      Protected Property Rows() As Integer
            Get
                  If Not ViewState("Rows") Is Nothing Then
                        Return CInt(Fix(ViewState("Rows")))
                  Else
                        Return 0
                  End If
            End Get
            Set(ByVal value As Integer)
                  ViewState("Rows") = value
            End Set
      End Property
 
      ' Columns property to hold the Columns in the ViewState
      Protected Property Columns() As Integer
            Get
             If Not ViewState("Columns") Is Nothing Then
                   Return CInt(Fix(ViewState("Columns")))
             Else
                   Return 0
             End If
            End Get
            Set(ByVal value As Integer)
                  ViewState("Columns") = value
            End Set
      End Property
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            ' Run only once a postback has occured
            If Page.IsPostBack Then
                  'Set the Rows and Columns property with the value
                  'entered by the user in the respective textboxes
                  Me.Rows = Int32.Parse(txtRows.Text)
                  Me.Columns = Int32.Parse(txtCols.Text)
            End If
            CreateDynamicTable()
 
 
End Sub
Observe over here that the values of the Rows and Columns properties are set only after the user enters the values and clicks the button, which causes the postback. That is the reason why we are checking against the If(Page.IsPostBack).
Step 3: On the button click, create the dynamic table as shown below. The code has been commented to help you understand.
C#
protected void btnGenerate_Click(object sender, EventArgs e)
    {
        CreateDynamicTable();
    }
 
 
    private void CreateDynamicTable()
    {
        PlaceHolder1.Controls.Clear();
 
        // Fetch the number of Rows and Columns for the table 
        // using the properties
        int tblRows = Rows;
        int tblCols = Columns;
        // Create a Table and set its properties 
        Table tbl = new Table();
        // Add the table to the placeholder control
        PlaceHolder1.Controls.Add(tbl);
        // Now iterate through the table and add your controls 
        for (int i = 0; i < tblRows; i++)
        {
            TableRow tr = new TableRow();
            for (int j = 0; j < tblCols; j++)
            {
                TableCell tc = new TableCell();
                TextBox txtBox = new TextBox();
                txtBox.Text = "RowNo:" + i + " " + "ColumnNo:" + " " + j;
                // Add the control to the TableCell
                tc.Controls.Add(txtBox);
                // Add the TableCell to the TableRow
                tr.Cells.Add(tc);
            }
            // Add the TableRow to the Table
            tbl.Rows.Add(tr);
        }
 
       // This parameter helps determine in the LoadViewState event,
       // whether to recreate the dynamic controls or not
 
       ViewState["dynamictable"] = true;
    }
 
VB.NET
Protected Sub btnGenerate_Click(ByVal sender As Object, ByVal e As EventArgs)
            CreateDynamicTable()
End Sub
 
 
      Private Sub CreateDynamicTable()
            PlaceHolder1.Controls.Clear()
 
            ' Fetch the number of Rows and Columns for the table 
            ' using the properties
            Dim tblRows As Integer = Rows
            Dim tblCols As Integer = Columns
            ' Create a Table and set its properties 
            Dim tbl As Table = New Table()
            ' Add the table to the placeholder control
            PlaceHolder1.Controls.Add(tbl)
            ' Now iterate through the table and add your controls 
            For i As Integer = 0 To tblRows - 1
                  Dim tr As TableRow = New TableRow()
                  For j As Integer = 0 To tblCols - 1
                        Dim tc As TableCell = New TableCell()
                        Dim txtBox As TextBox = New TextBox()
                        txtBox.Text = "RowNo:" & i & " " & "ColumnNo:" & " " & j
                        ' Add the control to the TableCell
                        tc.Controls.Add(txtBox)
                        ' Add the TableCell to the TableRow
                        tr.Cells.Add(tc)
                  Next j
                  ' Add the TableRow to the Table
                  tbl.Rows.Add(tr)
            Next i
 
         ' This parameter helps determine in the LoadViewState event,
         ' whether to recreate the dynamic controls or not
 
         ViewState("dynamictable") = True
      End Sub
 
Step 4: The last piece of code is to determine whether to recreate the controls based on the ViewState[“dynamictable”]. Here’s how it works. The first time the page loads, the  LoadViewState() does not execute. The ViewState[“dynamictable”] flag is initialized once the button click occurs. When the postback occurs on the second button click (btnPost), it is then that our code written for overriding the LoadViewState() runs. The base.LoadViewState() instantiates the ViewState object. We then check the value of our ViewState flag, and based on the result, re-create our Table.
C#
    // Check the ViewState flag to determine whether to
    // rebuild your table again
    protected override void LoadViewState(object earlierState)
    {
        base.LoadViewState(earlierState);
        if (ViewState["dynamictable"] == null)
            CreateDynamicTable();
    }
VB.NET
' Check the ViewState flag to determine whether to
      ' rebuild your table again
      Protected Overrides Sub LoadViewState(ByVal earlierState As Object)
            MyBase.LoadViewState(earlierState)
            If ViewState("dynamictable") Is Nothing Then
                  CreateDynamicTable()
            End If
      End Sub
That’s it. Run the code. Enter the number of Rows and Columns to be created and click the Generate button to create the table. Since the table contains textboxes in each cell, manipulate the text inside the table and hit the ‘Cause Postback’ button. Even after the postback, the values of the table control are retained.
Note: If multiple controls of the same type are created, remember to create them with the same ID's.
I hope you now have a good idea now of how to create controls dynamically. You can adopt a similar approach to create any dynamic control in your application. I hope the article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.
 
 









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by Brett Spencer on Wednesday, April 16, 2008 9:05 PM
I have used this code over and over to try and get the bugs out but no matter what I do, I can not get the page to retain the controls after clicking on the "cause postback" button.  Also, I had to create an empty function for the buttonclick for button1 as I got an error first time around without doing so.  After reading the "Understanding ASP.NET View State" reference that was mentioned.  It seems to me that the controls should be rebuilt before the viewstate can load the saved information into them - somewhere in the page initialize stage.

I do not pretend to be an expert and if anything, I would call myself a beginner, so if I am missing some understanding to this process and the reason why all of the controls and information disapears when click on the "causes postback" button, I would appreciate a clearer discussion on exactly where the controls are being rebuilt as well as when the data (or state) is placed back into them.
Comment posted by Brett Spencer on Thursday, April 17, 2008 7:35 PM
I found the other error in this code...

      Protected Overrides Sub LoadViewState(ByVal earlierState As Object)
            MyBase.LoadViewState(earlierState)
            If ViewState("dynamictable") Is Nothing Then
                  CreateDynamicTable()
            End If
      End Sub

This should say:

        If Not ViewState("dynamictable") Is Nothing Then
            CreateDynamicTable()
        End If

This allows for the controls to be rebuilt and loads the saved information from viewstate back into the controls.

I tried to build the controls in OnInit() but like this articles states, it is very difficult to get the user input as a variable into the procedure in order to build the right amount of rows and columns.
Comment posted by Suprotim Agarwal on Friday, April 18, 2008 12:40 PM
Hi Brett..Thanks for the comment and pointing out the typo.You need to add the CreateDynamicTable() in the Page_Load(). I had missed it out while writing the article. I have now added the method. You do not have to change anything else.
Comment posted by bhavana on Wednesday, April 23, 2008 5:00 AM
I try to run this code in .net 2.0 with master page. but its not retaining postback value in dynamicaly created control.
Comment posted by DataBasic on Wednesday, May 14, 2008 10:30 AM
For master pages I added 'Handles Me.Load' to the Page_Load event as the following vb.net shows:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Comment posted by y2kstephen on Sunday, May 18, 2008 12:30 AM
thx a lot! this is exactly what i am looking for!
but i got a question...
after generate the rows and input something
the textboxes always rollback to default value for the FIRST postback click
but its all fine for the second or more postback clicks, the changes remained
did i do something wrong?
Comment posted by y2kstephen on Sunday, May 18, 2008 12:36 AM
thx a lot! this is exactly what i am looking for!
but i got a question...
after generate the rows and input something
the textboxes always rollback to default value for the FIRST postback click
but its all fine for the second or more postback clicks, the changes remained
did i do something wrong?
Comment posted by Suprotim Agarwal on Monday, May 19, 2008 9:16 PM
Hi,
Well that shouldn't be happening. The sample posted takes care of that.
Comment posted by Mike on Friday, May 30, 2008 6:37 PM
y2kstephen: the problem is that "ProcessPostData Second Try" fires after the Page Load on postback and resets the viewstate tracked values for the controls created during page load.  See http://yakkowarner.blogspot.com/2008/01/aspnet-dynamic-controls-and-viewstate.html
Comment posted by Francois Ward on Monday, June 02, 2008 1:06 PM
After spending much of the dawn of ASP.NET having to pull dynamically created controls, with all the issues that come with it (if you need viewstate, you have to create them in Init...but if you NEED viewstate, you need to make em on load, but then no viewstate!... exactly what this article tries to adress), I've finally come to the conclusion...

The best way to create controls dynamically on the page is to..not do it. Instead, make a custom CompositeControl, override CreateChildControl, have the properties of your control at the top level (with viewstate backing), and when a property change, set ChildControlsCreated to false, and you're set.

Fact is, -when- controls must be created or recreated "depends", and its what confuse people... what info to save, when to read it, when to create controls, what would be the consequences if I need to change the control structure... the CompositeControl base class handles all of that in a quite elegant way, and keeps your code behind cleaner. The first one is tricky to make, but once you get the philosophy behind it, everything purrs along...
Comment posted by CR on Monday, June 02, 2008 1:39 PM
Francois: That sounds interesting. Do you have any code examples of doing that?
Comment posted by Maan on Saturday, June 07, 2008 4:26 AM
Very cool. In each cell you had created textbox. What if we can give control to user to specify that what they require in a row? I think it will be more interesting...
Comment posted by Ehsan Moezzi on Monday, June 09, 2008 8:37 AM
Thank you to give it help
Comment posted by vinitha on Wednesday, June 11, 2008 8:05 AM
Hi, Good sample.
But this works only for the first time. when i again click the button the controls are not generated again. My requirement is to generate controls as many times as user clicks on the button. Please do help me in doing this.
Thanks in advance.
Comment posted by 6 on Tuesday, July 29, 2008 5:57 AM
a
Comment posted by Zeeshan Raees on Monday, August 18, 2008 5:32 AM
Nice Article thx buddy :)
Comment posted by meeran on Monday, September 15, 2008 4:50 PM
peace be upon u,
sir,
i have a doubt..
i need to add and remove table dynamically.and need to do cleint and server side validation for that.
my model is
https://20db.banner-admin.com/order/configure
how they do that.
i am a trainee in web design.i try to do like that.i not know how they did.pls teach that to me.
thanks

yours truely...
    meeran...
Comment posted by Faheem Sial on Tuesday, September 16, 2008 5:40 AM
Hi,This code was realy so helpfull for me thanx dear, could u plz guide me to access these controls values i placed a DropDownList into cell how could i access its selected index.Regards
Comment posted by Suprotim Agarwal on Tuesday, September 16, 2008 9:14 AM
meeran: Are you referring to the code when you select the banners and click continue. If yes, then create a user control with the required fields and add the user control dynamically for the no. of banners selected. I choose user controls since the banner content is the same throughout which will result in reusability

Faheem: You would need to loop through the rows and column collection of the dynamically created table. You can use FindControl from the cell or try out the cell's controls collection. I hope you have addded the DDL with an ID.

Comment posted by madankumar on Thursday, September 25, 2008 4:36 AM
Create a Table Dynamically in ASP.NET 2.0 and read excel value and pass the values into table .After editing store it to DB. Get the values from DB and pass it table again.
Comment posted by John K on Friday, November 07, 2008 6:32 PM
This is a great article and it help me out so much.  I am new at this and was wondering about how I can change the size of the text box's and also take the values that were inputed in the text and submit them to a SQL Database.  

I know how to submit them to a SQL database, but just not what the values are.  For example, textbox1.text would be the value entered in the text box.
Comment posted by John K on Friday, November 07, 2008 6:38 PM
This is a great article and it help me out so much.  I am new at this and was wondering about how I can change the size of the text box's and also take the values that were inputed in the text and submit them to a SQL Database.  

I know how to submit them to a SQL database, but just not what the values are.  For example, textbox1.text would be the value entered in the text box.
Comment posted by John K on Monday, November 10, 2008 9:51 AM
This is a great article and it help me out so much.  I am new at this and was wondering about how I can change the size of the text box's and also take the values that were inputed in the text and submit them to a SQL Database.  

I know how to submit them to a SQL database, but just not what the values are.  For example, textbox1.text would be the value entered in the text box.
Comment posted by John K on Monday, November 10, 2008 11:39 AM
This is a great article and it help me out so much.  I am new at this and was wondering about how I can change the size of the text box's and also take the values that were inputed in the text and submit them to a SQL Database.  

I know how to submit them to a SQL database, but just not what the values are.  For example, textbox1.text would be the value entered in the text box.
Comment posted by Tony on Monday, November 10, 2008 12:38 PM
Hmm, well I was able to get this code working only after removing CreateDynamicTable() from Page_Load() and putting it in OnInit(), also had to set the ID for each TextBox otherwise the value wouldn't always appear in the correct TextBox upon the restore of the values.
Comment posted by Suprotim Agarwal on Tuesday, November 11, 2008 11:56 AM
John: There are multiple ways to update values to the db.

One could be by using ExecuteNonQuery on the command object or if you are using a datasource control like SQLDataSource to fetch records, you can use the same to update values from the textbox as well

<asp:SqlDataSource ID="SqlDataSource1" runat="server" InsertCommand="INSERT INTO Customers(Name, Age) VALUES ( @Param1 , @Param2 )"
                ConnectionString="<%$ ConnectionStrings:YourConnStringName %>">
                <InsertParameters>
                    <asp:ControlParameter ControlID="TextBox1" DefaultValue="" PropertyName="Text" Name="Param1" />
                    <asp:ControlParameter ControlID="TextBox2" DefaultValue="" PropertyName="Text" Name="Param2" />
                </InsertParameters>
            </asp:SqlDataSource>

Then on the button click, call SQLDataSource1.Insert()

Tony: I have used the Page_Load for a specific purpose and have also described it in the article. Thanks for your comment though.
Comment posted by Manoj on Monday, December 29, 2008 3:32 AM
How to save the values while entering the data in dynamic table
Comment posted by Manoj on Monday, December 29, 2008 4:53 AM
How to assign a label for place holder
Comment posted by Manoj on Wednesday, December 31, 2008 4:14 AM
How to get the value from placeholder and save into the database
Comment posted by Rahul Shinde on Tuesday, January 13, 2009 5:57 AM
it is great it will help me lots
Comment posted by mathan on Thursday, January 22, 2009 5:19 AM
if any one know plz send me
Comment posted by prabhat22 on Wednesday, February 11, 2009 6:34 AM
hi
I have created table using above method.
but now iam facing problem to store the values to database.
how to accept the values from dyanmictable and send it to database.
Comment posted by hardik patel on Thursday, April 09, 2009 2:45 AM
I have used this code over and over to try and get the bugs out but no matter what I do, I can not get the page to retain the controls after clicking on the "cause postback" button.  Also, I had to create an empty function for the buttonclick for button1 as I got an error first time around without doing
Comment posted by Than Than Aye on Thursday, April 30, 2009 5:23 AM
I can not run.Errors occur CreateDynamicTabel().
Comment posted by Shrikrishna on Friday, May 08, 2009 6:51 AM
I have used this code for generating table rows dinamically.
Now i want to retrive the table values and want to insert that values into the database. how can i get all the values when am clicking save button ? Help me plz....
Comment posted by ynnorj on Friday, June 12, 2009 4:10 AM
I also have a problem retrieving values per textbox. But the textbox created are not <asp:textbox> (or are they?);
and if I pull up the data from each textbox, I also need to assign each a different Id. But if I assign them IDs, the Ids wouldn't be recognized as well because they are set as local variables.

Aren't there no textbox arrays where we could just simply search for the variablename[index]? Thank you.
Comment posted by Aarathy Kulathunkal on Thursday, July 23, 2009 12:47 AM
It was very useful for me. I could create dynamic table...Thank you soooo much.
Comment posted by DST on Wednesday, August 05, 2009 2:54 PM
Hi, it's very useful and I was able to create a dynamic table & keeping it's earlier state using the 'LoadViewState'....But 'Page.PreviousPage' is not working when I call thru the LoadViewState. Pls check below code and let me know what I am doing wrong or way to fix it !!!
------------------------------------------------------------------------------------
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  If Not Page.IsPostBack Then
      CreateDynamicTable() '--- It's working fine at page load...
  End If
end sub
----------------------------------------------------------------------------
Protected Overrides Sub LoadViewState(ByVal earlierState As Object)
   MyBase.LoadViewState(earlierState)
   If Not ViewState("dynamictable") Is Nothing Then
      CreateDynamicTable() '--- It's failed to find a previous page...
   End If
End Sub
--------------------------------------
Protected Sub CreateDynamicTable()
    Dim previousPageTable as Table = CType(Page.PreviousPage.FindControl("TBL"), Table)  
     'It's not finding the previouspage when this method was called from 'LoadViewState'.
   ....
   ....
   ....
  ViewState("dynamictable") = True
end sub
Comment posted by Sinu on Thursday, October 15, 2009 3:31 AM
How can i insert the data in the dynamic table to sql server table using c# please help thanx in advance
Comment posted by msk on Tuesday, October 27, 2009 12:57 PM
Hi, thanks for this article, can you please tell me how to reterive the data from each textbox , I want to store back in the database..

Thanks
MSK
Comment posted by Bhavan on Tuesday, November 24, 2009 1:32 AM
Hi, Thanks for the article. But as I am newbie, unable to run the codes successfully and getting the 'Button1_Click' is not a member of 'ASP.default_aspx' error message. I found that nothing is there in the article for button1_click event. Please provide the code so that the created table to display on the page.
Thanks, Bhavan
Comment posted by Suprotim Agarwal on Tuesday, November 24, 2009 4:36 AM
Bhavan: Just double click on the Button and it will generate the code behind for the button click. It's there to simply cause a postback.

Comment posted by Bhavan on Tuesday, November 24, 2009 6:28 AM
Hi Suprotim,
Thanks for your immediate reply.
But I didn't get any result while giving any values and clicking on generate table. Even nothing returned clicking on cause postback. Please suggest.

Bhavan  
Comment posted by chaithu on Thursday, December 10, 2009 2:31 AM
Thanks for your immediate reply.
But I didn't get any result while giving any values and clicking on generate table. Even nothing returned clicking on cause postback. Please
Comment posted by Luca on Monday, December 14, 2009 11:59 AM
hi Suprotim, Thanks for the article, it's been really helpfull. Unfortunatelly i have the same trouble as  y2kstephen  : "the textboxes always rollback to default value for the FIRST postback click
but its all fine for the second or more postback clicks, the changes remained ". What should i do with it?? You answered him that the code should take care of that case too but i can't solve the problem.... Please suggest.
Comment posted by vikky on Thursday, January 28, 2010 5:06 AM
Good,but my question is that how to save dynamic generated table in to database.
Comment posted by fazail on Tuesday, February 02, 2010 4:50 AM
i have used it butr iit is uncompled
Comment posted by Jafar on Tuesday, February 02, 2010 7:02 AM
It’s a good program; however I am interested to find out how to transfer these tables into a database “as per previous commenter”.
Comment posted by Dharmeshwari on Wednesday, February 10, 2010 11:56 PM
This article is very good for understanding both the concept and as well as the implementation. I worked it out. Also i was struggling for this code in the net for long time... it helped me a lot... Thakn u so much....
Comment posted by simflex on Wednesday, March 10, 2010 1:30 PM
This is an absolute mastermind. I looked for this solution for a long time till now.

Thank you very, very much.

I just have one question though. If I don't want the text on the boxes after they are created like: RowNo:0 ColumnNo: 0,  RowNo:0 ColumnNo: 1,RowNo:0 ColumnNo: 2..., how do I get rid of them?

Again, great work; thanks
Comment posted by simflex on Wednesday, March 10, 2010 2:07 PM
This is an absolute mastermind. I looked for this solution for a long time till now.

Thank you very, very much.

I just have one question though. If I don't want the text on the boxes after they are created like: RowNo:0 ColumnNo: 0,  RowNo:0 ColumnNo: 1,RowNo:0 ColumnNo: 2..., how do I get rid of them?

Again, great work; thanks
Comment posted by Simflex on Tuesday, March 16, 2010 11:48 AM
Does anyone know how to *not* show those text on the boxes once the columns and rows are created?

As you know once the number of rows and columns are created, you see text such as RowNo:0 ColumnNo: 0; RowNo:0 ColumnNo: 1; RowNo:0 ColumnNo: 2, etc.

I want to either hide them or remove them from displaying on the cells.

Thanks a for quick reponse on this.
Comment posted by Sudipto on Wednesday, March 17, 2010 2:58 AM
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            this.Rows = Int32.Parse(TextBox1.Text);
            //I am getting "System.FormatException: Input string was not in a correct format." on the above line

        }
        generate_table(); //my version of CreateDynamicTable()  
    }

I am using your code in a content page which has a page template.
Comment posted by Naveen on Tuesday, April 20, 2010 5:54 AM
How to get these text box values
Comment posted by surzo4368 on Monday, May 03, 2010 4:18 AM
i try this but table not generated just page refresh. help...
Comment posted by zhugw519 on Wednesday, May 12, 2010 3:35 AM
It's very useful to me,thanks a lot!
Comment posted by jia on Saturday, June 05, 2010 7:10 AM
I want to save the contents of a webpage in a database table by using a Htmleditor. Contents of htmleditor are saved in database in form of htmlcode. I am able to successfully save data in database but i am unable to retrieve the saved data back in form of designed webpage.

The data on this page is retrieve from database table field. Table has fields like id, title, detail. title field has title of a page, detail field has complete detail of a web page which is save in database in the form of htmlcode. The problem is that how a web page is designed from this, how I am show these contents in detail section of a asp.net masterpage.
I am using sqlserver and asp.net with vb not C#.

Anyone help me.
Thanks in advance
Comment posted by tejender on Friday, June 11, 2010 7:12 AM
nice
Comment posted by Saif on Wednesday, June 16, 2010 3:06 AM
You have done a nice work! thanks for sharing, i just wanted to know that how could i get the values of the text boxes after clicking the Cause Postback button suppose i inserted data into the text boxes????
Please i need your urgent help!

regards
Comment posted by Abhinesh Rao on Monday, June 28, 2010 6:14 PM
Hi Suprotim,

I just wanted to know how do I create the tables dynamically, when I enter a number either in the ROW or the COLUMN field it starts loading and then I am not able to enter value in the other field(ROW/COLUMN) which results in a null exception.

Thanks for your kind help
Comment posted by Prashant on Monday, July 19, 2010 6:59 AM
Hi Suprotim,

Thanks for this great article i wanted the exact code ,but i wasn't successful in getting the result as u said, i'm having problem maintaining the viewstate ,once clicked on cause post back the textboxes return to their default value.
Hope you reply soon
Thanks & Regards


  
Comment posted by Camilo Torregroza on Wednesday, July 21, 2010 4:53 PM
Hi thank you  for your post.

I'm trying to add a dropdownlist, a textbox and a button the dropdownlist will display some products list, and the button it's for delete the entire row.

also I have a button to add new rows to the table but it's out of the table.
when I'll try to add more than twice a row i had an exception:
I'll appreciate if you can help me with this. thank you.
this is my code if you could help me.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ControlAgregarProducto.ascx.cs"
    Inherits="ClienteWeb.Controls.ControlAgregarProducto" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<style type="text/css">
    .style1
    {
        height: 23px;
        width: 157px;
    }
    .style2
    {
        width: 157px;
    }
    .style3
    {
        height: 23px;
        width: 104px;
    }
    .style4
    {
        width: 104px;
    }
</style>
<%--<asp:UpdatePanel>
    <ContentTemplate>--%>
<table style="width: 100%" title="Stems">
    <tr>
        <td class="style1">
        </td>
        <td class="style3">
        </td>
        <td style="height: 23px; width: 263px">
        </td>
        <td style="height: 23px; width: 263px">
            &nbsp;
        </td>
    </tr>
    <tr>
        <td class="style2">
            Product
        </td>
        <td class="style4">
            &nbsp;
        </td>
        <td style="width: 263px">
            Quantity
        </td>
        <td style="width: 263px">
            &nbsp;
        </td>
    </tr>
    <tr>
        <td colspan="4">
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        </td>
    </tr>
    <tr>
        <td class="style2">
            &nbsp;
        </td>
        <td class="style4">
            &nbsp;
        </td>
        <td style="width: 263px">
            &nbsp;
        </td>
        <td style="width: 263px">
            &nbsp;
        </td>
    </tr>
    <tr>
        <td class="style2">
            <strong>Total</strong>
        </td>
        <td class="style4">
            &nbsp;
        </td>
        <td style="width: 263px">
            [<asp:Button ID="btnAdd" runat="server" BackColor="White" BorderColor="White" BorderStyle="None"
                Text="Add" Font-Bold="True" Height="15px" OnClick="btnAdd_Click" />
            ]
        </td>
        <td style="width: 263px">
            &nbsp;
        </td>
    </tr>
</table>
<%--    </ContentTemplate>
</asp:UpdatePanel>--%>

___________
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FF.ClienteWebBL;

namespace ClienteWeb.Controls
{
    public partial class ControlAgregarProducto : System.Web.UI.UserControl
    {
        protected int Rows
        {
            get
            {
                return ViewState["Rows"] != null ? (int)ViewState["Rows"] : 0;
            }
            set
            {
                ViewState["Rows"] = value;
            }
        }

        protected int Columns
        {
            get
            {
                return ViewState["Columns"] != null ? (int)ViewState["Columns"] : 0;
            }
            set
            {
                ViewState["Columns"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Run only once a postback has occured
            if (!Page.IsPostBack)
            {
                //Set the Rows and Columns property with the value
                //entered by the user in the respective textboxes
                this.Rows = 1;
                this.Columns = 3;
                this.EnableViewState = true;
                
            }

            CreateDynamicTable();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            this.Rows += 1;
            CreateDynamicTable();
            
        }

        private void CreateDynamicTable()
        {
            PlaceHolder1.Controls.Clear();

            // Fetch the number of Rows and Columns for the table
            // using the properties
            int tblRows = Rows;
            int tblCols = Columns;
            // Create a Table and set its properties
            Table tbl = new Table();
            // Add the table to the placeholder control
            PlaceHolder1.Controls.Add(tbl);
            // Now iterate through the table and add your controls
            ProductoFacade facadeProducto = new ProductoFacade();

            
            for (int i = 0; i < tblRows; i++)
            {

                TableRow tr = new TableRow();
                TableCell tCell1 = new TableCell();
                DropDownList ddlProducto = new DropDownList();
                ddlProducto.DataSource = facadeProducto.GetEspecies();
                ddlProducto.DataTextField = "Nombreingles";
                ddlProducto.DataValueField = "Idespecie";
                ddlProducto.DataBind();

                tCell1.Controls.Add(ddlProducto);
                TableCell tEmptyCell2 = new TableCell();
                
                TableCell tCell3 = new TableCell();
                TextBox txtQuantity = new TextBox();

                TableCell tCell4 = new TableCell();
                Button btnDeleteProducto = new Button();
                
                //btnDeleteProducto.BorderStyle = BorderStyle.None;
                //btnDeleteProducto.BorderColor = System.Drawing.Color.White;
                //btnDeleteProducto.Text = "Delete";
                //btnDeleteProducto.Click += new EventHandler(btnDeleteProducto_Click);
                tCell3.Controls.AddAt(0,txtQuantity);
                tCell4.Controls.AddAt(0,btnDeleteProducto);

                tr.Cells.Add(tCell1);
                tr.Cells.Add(tEmptyCell2);
                tr.Cells.Add(tCell3);
                tr.Cells.Add(tCell4);

                tbl.Rows.Add(tr);
            }

            // This parameter helps determine in the LoadViewState event,
            // whether to recreate the dynamic controls or not
            ViewState["dynamictable"] = true;
        }

        void btnDeleteProducto_Click(object sender, EventArgs e)
        {
            Control boton = (Control)sender;
            
        }

        protected override void LoadViewState(object earlierState)
        {
            base.LoadViewState(earlierState);
            if (ViewState["dynamictable"] == null)
                CreateDynamicTable();
        }
    }
}
The exception is :

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.
I hope you could help mw with this..

Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER