Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

In my previous example, I wrote a simple demo on how to generate rows of TextBoxes in ASP Table on every click of the Button and retain the previous values on postbacks. In this article, I’m going to extend a bit of what I have shown in my previous example.

Basically, I’m going to add multiple delete functionality in the Table by adding some rows of CheckBoxes.

Here are the code blocks below:

ASPX
SOURCE VIEW:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Dynamic Adding of Rows in ASP Table with Multiple Deletion Demo</title>

    <script type="text/javascript">

</head>

<body>

    <form id="form1" runat="server">

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" /> &nbsp;

    <asp:Button ID="Button2" runat="server" Text="Remove Selected Row(s)"

        onclick="Button2_Click" />

    </form>

    </body>

</html>

 

RELEVANT CODES:

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class _Default1 : System.Web.UI.Page

{

    //A global variable that will hold the current number of Rows

    //We set the values to 1 so that it will generate a default Row when the page loads

    private int numOfRows = 1;

  

 

    protected void Page_Load(object sender, EventArgs e)

    {

        //Generate the Rows on Initial Load

        if (!Page.IsPostBack)

        {

            GenerateTable(numOfRows);

        }

 

    }

 

    protected void Button1_Click(object sender, EventArgs e)

    {

        if (ViewState["RowsCount"] != null)

        {

            numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());

            GenerateTable(numOfRows);

        }

    }

 

    protected void Button2_Click(object sender, EventArgs e)

    {

        GetSelectedRows();

    }

 

    private void SetPreviousData(int rowsCount, int colsCount)

    {

        Table table = (Table)Page.FindControl("Table1");

        if (table != null)

        {

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

            {

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

                {

                    if (j == 0)

                    {

                        //Get the Checked value of the CheckBox using the Request objects

                        string check = Request.Form["CheckBoxRow_" + i + "Col_" + j];

                        //Extract the CheckBox Control from within the Table

                        CheckBox cb = (CheckBox)table.Rows[i].Cells[j].FindControl("CheckBoxRow_" + i + "Col_" + j);

                        if (check == "on") //If selected

                        {

                            cb.Checked = true;

                        }

                    }

                    else

                    {

                        TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);

                        tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];

                    }

                }

            }

        }

    }

 

    private void GenerateTable(int rowsCount)

    {

        //Creat the Table and Add it to the Page

        Table table = new Table();

        table.ID = "Table1";

        Page.Form.Controls.Add(table);

 

        //The number of Columns to be generated

        const int colsCount = 3;//You can changed the value of 3 based on you requirements

 

        // Now iterate through the table and add your controls

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

        {

            TableRow row = new TableRow();

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

            {

                TableCell cell = new TableCell();

 

                if (j == 0) //means the first column of the Table

                {

                    //Create the CheckBox

                    CheckBox cb = new CheckBox();

                    // Set a unique ID for each CheckBox

                    cb.ID = "CheckBoxRow_" + i + "Col_" + j;

                    // Add the control to the FIRST TableCell

                    cell.Controls.Add(cb);

                    // Add the TableCell to the TableRow

                    row.Cells.Add(cell);

                   

                }

                else

                {

                    //Create the TextBox

                    TextBox tb = new TextBox();

                    // Set a unique ID for each TextBox

                    tb.ID = "TextBoxRow_" + i + "Col_" + j;

                    // Add the control to the TableCell

                    cell.Controls.Add(tb);

                    // Add the TableCell to the TableRow

                    row.Cells.Add(cell);

                }

            }

 

            // And finally, add the TableRow to the Table

            table.Rows.Add(row);

        }

 

        //Set Previous Data on PostBacks

        SetPreviousData(rowsCount, colsCount);

 

        //Sore the current Rows Count in ViewState

        rowsCount++;

        ViewState["RowsCount"] = rowsCount;

    }

 

    private void GetSelectedRows()

    {

        if (ViewState["RowsCount"] != null)

        {

            numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());

            int removedRows = numOfRows - 1;

 

            //Re create the Table on Postbacks

            GenerateTable(numOfRows - 1);

 

            Table table = (Table)Page.FindControl("Table1");

            if (table != null)

            {

                if (table.Rows.Count > 0)

                {

                    for (int i = table.Rows.Count - 1; i >= 0; i--)

                    {

                        //Get the Checked value of the CheckBox using the Request objects

                        string check = Request.Form["CheckBoxRow_" + i + "Col_" + 0];

                        //Extract the CheckBox Control from within the Table

                        if (check == "on") //If selected

                        {

                            table.Rows.Remove(table.Rows[i]);

                            removedRows--;

                        }

                    }

                    ViewState["RowsCount"] = removedRows + 1;

                }

            }

        }

    }

}

 

In the above implementation, I used ViewState to maintain the row count of the Table across postbacks and used the request objects to get the posted data to the server.

Now here’s how the rendered page looks like:

On Initial Load:



After Adding some Rows:



Selecting Rows to be Deleted:



After Deletion of the Selected Rows:




That's it! Hope you will find this example useful!

 

Technorati Tags: ,,
Posted on Wednesday, July 1, 2009 5:05 AM ASP.NET , C# | Back to top


Comments on this post: Adding Dynamic Editable Rows in ASP Table with Multiple Delete

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete
Requesting Gravatar...
Vinz,

Thank you very much for your useful example. Let's say we have three rows 1 2 3. Then, I decide to remove row 2. Now we have left row1 and row3. How would I insert values of row1 and row2 to database when I use the for loop? Would you mind give me an example how to insert values to DB?

Again, thank you for your useful blog!
Left by Zenitu on Jul 11, 2009 6:09 PM

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete
Requesting Gravatar...
Thank you for your quick reply. I look forward into your example.

I have another question. I hope you can give me some suggestions. I tried your implementation, and it worked well without a Master page. However, it does not work if I have a page with a Master page. I tried to find the control Table1, but it did not. Here is my little code:

ContentPlaceHolder mainContent = (ContentPlaceHolder)(this.Master.FindControl("mainContentHolder"));
Table table = (Table)mainContent.FindControl("Table1");

Could you tell me what's wrong with my code?

I truly appreciate your help.
Left by Zenitu on Jul 12, 2009 1:32 PM

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete
Requesting Gravatar...
Hi Vinz,

I tried your code above. After your last example where only 3 rows left with the data 3, 5 and an empty data. I add rows again and found the data are incorrect. Please advise.

By the way, thanks for your code which is very helpful for me :)

Cheers,
Cindy
Left by cyndi on Nov 11, 2009 8:32 PM

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete
Requesting Gravatar...
thanks Vinz and hope to hear from you soon :)
Left by Cindy on Nov 15, 2009 5:02 PM

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete
Requesting Gravatar...
thanx that really helped me
Left by kitty on Mar 09, 2010 5:02 PM

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete
Requesting Gravatar...
This really helped me too thank you.
Left by Udaya on Dec 30, 2010 5:58 PM

# re: adding multilple records into plsql using loop in asp code
Requesting Gravatar...
i have inserted multiple rows, i am able to insert only one record but i want to insert multiple records with the help of loop in asp code using vbscript
Left by shwetha on May 30, 2012 4:19 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net