user123456789
user123456789

Reputation: 2004

How to loop through a DataGrid?

I know this may sound like a very basic question but most examples I find are for GridView.

I just want to a foreach loop that goes through each row of the DataGrid. DataGrid dgDetails = new DataGrid();

I tried foreach (DataGridItem dataGridItem in dgDetails.Items)

but it skipped over this because it didn't find any Items.

I want to do something like this:

foreach (GridViewRow row in GridView1.Rows)
{
    if (row.RowIndex % 10 == 0 && row.RowIndex != 0)
    {
         row.Attributes["style"] = "page-break-after:always;";
    }
 }

But I need to change it to work for a DataGrid. I am trying to insert a page break after the tenth row. But I know DataGrid does not contain a definition for 'Rows' so what can be used instead?

Upvotes: 0

Views: 6004

Answers (1)

CWeaver
CWeaver

Reputation: 41

As previously noted in the comments of the question, DataGrid does not have a .Rows method. Using foreach (DataGridItem dataGridItem in dgDetails.Items) is the way to iterate through the rows of a DataGrid. You will need to make sure to set your source and do a data bind before doing the foreach loop.

    DataGrid dgDetails = new DataGrid();
    dgDetails.DataSource = your source
    dgDetails.DataBind();
    foreach (DataGridItem dataGridItem in dgDetails.Items)
    {
        //Do things with the dataGridItem here.
    }

Upvotes: 2

Related Questions