Reputation: 424
In my windows form, I am having 10 datagridview. They are exactly same, I mean columns are exactly same. The ids are like myGrid1,myGrid2, myGrid3, myGrid4.....myGrid10. Now I want to loop through all datagridview at once.
string prodName = "";
for (int i = 1; i <= 10; i++)
{
foreach (DataGridViewRow dr in myGrid[i].Rows)
{
prodName += dr.Cells["ProductName"].Value
}
}
but myGrid[i] doesn't exists obviously. I can loop each datagridview seperately but is there any easy way to do this?
Upvotes: 0
Views: 1480
Reputation: 14024
Hope this helps.
foreach (Control x in this.Controls)
{
if (x is DataGridView)
{
foreach (DataGridViewRow dr in (DataGridView(x)).Rows)
{
prodName += dr.Cells["ProductName"].Value
}
}
}
or
foreach ( DataGridView dgv in this.Controls.OfType<DataGridView>())
{
foreach (DataGridViewRow dr in dgv.Rows)
{
prodName += dr.Cells["ProductName"].Value
}
}
Upvotes: 1