Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 366, trackbacks - 0

My Links

News

Archives

Image Galleries

Adding Dynamic Editable Rows in ASP Table with Multiple Delete

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!

Print | posted on Wednesday, July 01, 2009 5:05 AM |

Feedback

Gravatar

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete

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!
7/11/2009 6:09 PM | Zenitu
Gravatar

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete

Hi Zenitu,

You can loop through the Table as what I did in the SetPreviousData() method to get the values from the TextBox.. you can then use Request.Form to get the actual data and insert that to your database.

PS: I will try to create an example on how to get the dynamic data from the table and store it in the database soon..
7/12/2009 12:56 AM | Vinz
Gravatar

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete

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.
7/12/2009 1:32 PM | Zenitu
Gravatar

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete

Hi Zenitu,

Try to check this article:

http://www.west-wind.com/Weblog/posts/5127.aspx
7/12/2009 1:39 PM | Vinz
Gravatar

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete

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
11/11/2009 8:32 PM | cyndi
Gravatar

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete

@Cindy,

Let me try to reproduce it.. I will just update you once after.
11/11/2009 9:56 PM | Vinz
Gravatar

# re: Adding Dynamic Editable Rows in ASP Table with Multiple Delete

thanks Vinz and hope to hear from you soon :)
11/15/2009 5:02 PM | Cindy
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: