jackncoke
jackncoke

Reputation: 2020

How to foreach though TableRows

I need to improve a table

I add rows to this table using C#.

  foreach (var item in items)
            {
                TableRow row = new TableRow();
                TableCell cell = new TableCell();
                LinkButton lb2 = new LinkButton();
                CheckBox chk = new CheckBox();
                chk.CssClass = "chkBox";
                lb2.CommandArgument = item.id.ToString();
                lb2.Text = item.cat_name;
                lb2.ID = "lb" + item.id.ToString();
                lb2.Click += new EventHandler(lb_Click);
                Label lbl = new Label();
                lbl.Text = "    ";
                LinkButton lb3 = new LinkButton();
                lb3.CommandArgument = item.id.ToString();
                lb3.ID = "lb3" + item.id.ToString();
                lb3.Text = "Edit/Delete";
                lb3.Click += new EventHandler(lb2_Click);
                cell.Controls.Add(chk);
                cell.Controls.Add(lb2);
                cell.Controls.Add(lbl);
                cell.Controls.Add(lb3);
                row.Cells.Add(cell);
                tblitems.Rows.Add(row);
            }

Now i need to write another method that allows me what checkboxes are checked in the table. So that I can delete the checked rows.

This is what i have.

protected void DeleteAll_Click(object sender, EventArgs e)
    {

        var mytable = (Table)FindControl("tblitems");

        foreach (TableRow row in mytable)
        {
            var myChkBox = (CheckBox)mytable.FindControl("chkBox");
            var myhiddenfield = (HiddenField)mytable.FindControl("hiddenID");

            if (myChkBox.Checked)
            {
                //Delete record 
              Response.Write("Record" + myhiddenfield.Value + "Has been deleted");
            }

        }

    }

I get a error foreach statement cannot operate on variables of type 'System.Web.UI.WebControls.Table' because 'System.Web.UI.WebControls.Table' does not contain a public definition for 'GetEnumerator'

Upvotes: 1

Views: 2498

Answers (2)

Glenn Cuevas
Glenn Cuevas

Reputation: 164

Bill's answer will fix your code behind, but you may want to consider using a Repeater or a GridView for creating tabular data that is associated with a datasource. The GridView already supports some basic editing/deleting, etc.

Here's a link that shows some of its usage: http://www.dotnetspider.com/resources/44926-GridView-Edit-Cancel-Update-Delete-ASP.net.aspx

Upvotes: 3

Bill Gregg
Bill Gregg

Reputation: 7147

You need to reference the Rows property of the table.

 foreach (TableRow row in mytable.Rows)

Upvotes: 6

Related Questions