Tutorial :Iterate through rows in an html table with C#



Question:

I have an html table in an aspx page (C#) that has columns like

 1.CheckBox  2.Text  3.Text  4.TextBox  

I want to iterate through the table one row at a time and process (run a stored procedure based on column2) based on whether the checkbox is checked or not. How will I be able to do that?


Solution:1

Assuming you're using the Table server control then it's just:

foreach (TableRow row in table.Rows)      {          var checkBox = (CheckBox)row.Cells[0].Controls[0]; //Assuming the first control of the first cell is always a CheckBox.            if (checkBox.Checked)          {              var col2 = (TextBox)row.Cells[1].Controls[0];                /* Do Stuff With col2 */          }          else          {              /* Do Stuff */          }      }  

If you're using just a regular html table (with runat="server") as well as html form controls then just change TableRow to HtmlTableRow, CheckBox to HtmlInputCheckBox, and TextBox to HtmlInputText. All of those controls are in the System.Web.UI.HtmlControls namespace.


Solution:2

I already had some VB.NET code handy that can do this. It just took a little tweaking. It could be ported over to C# easily.

Protected Sub Page_Load()      FindCheckBoxes(MyTable)  End Sub    Protected Sub FindCheckBoxes(ByRef ParentControl As Control)      For Each ctrl As Control In ParentControl.Controls          If TypeOf ctrl Is CheckBox Then              If DirectCast(ctrl, CheckBox).Checked Then                  ' do something              Else                  ' do something else              End If          ElseIf ctrl.HasControls Then              FindCheckBoxes(ctrl)          End If      Next  End Sub  

This is flexible enough to find checkboxes inside of anything (not just a table). However, in your particular scenario you may prefer to use something like noblethrasher's answer.

My answer is a recursive method of crawling through the tree, finding every single checkbox. But noblethrasher's is a simple, straightforward, and more efficient algorithm if you know which column to look for the checkbox and you know it's not buried inside additional containers.


Solution:3

Check out the HtmlTable class and its Rows property.

http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmltable(VS.71).aspx

I'm sure that can help you on the way!


Solution:4

If you add a runat="server" attribute to the table tag in html, you should be able to see the table as a collection of Control objects and you should be able to iterate through.

This seems like the worst possible way to achieve dynamic data, however. Perhaps with some background we could help you find a better way...


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »