Reputation: 20078
need help in tweaking my logic little bit.
as you see i have two foreach loop
and both for different columns in gridview
this code is in OnRowUpdating in the gridview for more info what exactly i am doing you can see the closed thread here
the problem is:
on every loop i will be updating a row to db but since i have two different loop it will not exit till the first loop finishes.
for an example: i have _rpt.Count = 2 so it will loop twice before it hit the second loop.
GridViewRow row = gv.SelectedRow;
Repeater _rpt = gv.Rows[e.RowIndex].Cells[8].FindControl("rptReg") as Repeater;
Repeater _rpt1 = gv.Rows[e.RowIndex].Cells[9].FindControl("rptVisitor") as Repeater;
foreach (RepeaterItem item in _rpt.Items)
{
TextBox _txt = item.FindControl("txtId") as TextBox;
TextBox _txt1 = item.FindControl("txtName") as TextBox;
//update db
}
foreach (RepeaterItem item1 in _rpt1.Items)
{
TextBox _txt3 = item1.FindControl("txtVisitor") as TextBox;
//update db
}
is there a way that i can read both foreach loop values?
Upvotes: 1
Views: 903
Reputation: 6348
If you're doing a loop through multiple collections, and want to access each collection more than once, than a foreach
may not be the best fit.
Try a regular for
loop instead:
for (int i = 0; i < _rpt.Items.Count; i++)
{
TextBox _txt = _rpt.Items[i].FindControl("txtId") as TextBox;
TextBox _txt1 = _rpt.Items[i].FindControl("txtName") as TextBox;
if (_rpt1.Items.Count > i)
TextBox _txt3 = _rpt1.Items[i].FindControl("txtVisitor") as TextBox;
//update db
}
The above will only work as expected if (_rpt.Items.Count >= _rpt1.Items.Count)
, so be sure to check for and use the collection with the most items if they are ever going to be different.
Using a foreach
loop enumerates the items within the single collection, allowing you a direct reference to each item within each iteration. This is handy if you are only accessing the one collection, as you don't need to use array indexers, and can just use the name you give it at the loop initialization.
It's not so handy when you are looping through multiple collections, as you ONLY have a reference to the collection used in the loop header.
Using a for
loop allows you to keep track of which index you are at (using an int
), allowing you to just use standard array notation to get the items in the collection.
Upvotes: 1
Reputation: 7539
foreach (RepeaterItem item in _rpt.Items)
{
TextBox _txt = item.FindControl("txtId") as TextBox;
TextBox _txt1 = item.FindControl("txtName") as TextBox;
//update db
TextBox _txt3 = _rpt1.Items[item.ItemIndex].FindControl("txtVisitor") as TextBox;
}
Upvotes: 1