Mronzer
Mronzer

Reputation: 449

How to select only first 100 rows on Gridview

I have gridview that contains check boxes in one of the columns, then there is a "Select ALl" button which when clicked has to check top 100 CBs on the list, the client specifically stated they do not want pagination, it much easier to do this with pagination and display only 100 records per page then when the select all button is clicked everything on the given page gets selected however this is not what the client wants

Here is my code:

foreach (GridViewRow row in dgridTransactions.Rows)
{
    for (int x = 0; x <=100;x++ )
    {
        var oneTransaction = (CheckBox)row.FindControl("chkAssigned");
        oneTransaction.Checked = true;
    }
}

Upvotes: 0

Views: 1042

Answers (4)

sp_m
sp_m

Reputation: 2707

using RowIndex you can keep track of row number.

foreach (GridViewRow row in dgridTransactions.Rows)
{
    if(row.RowIndex<100 )
    {
        var oneTransaction = (CheckBox)row.FindControl("chkAssigned");
        oneTransaction.Checked = true;
    }
    else
        break;

}

Upvotes: 1

Nuno Agapito
Nuno Agapito

Reputation: 230

How about:

foreach (GridViewRow row in dgridTransactions.Rows.Cast<GridViewRow>().Take(100)) {
    CheckBox cb = row.FindControl("chkAssigned") as CheckBox;
    if (cb != null)
      cb.Checked = true;
  }

This will give the first items up to 100, so if you only have 90, it will give 90. The diferent way of casting will also give you an additional security measure in case it fails to find the control. A direct cast will just throw an exception, which is always heavier then checking if the castes object is not null...

If you dont care about the cast verification, you can just inline everything into this:

dgridTransactions.Rows.Cast<GridViewRow>().Take(100).ToList().ForEach(x => ((CheckBox)x.FindControl()).Checked = true);

Upvotes: 0

शेखर
शेखर

Reputation: 17614

There is issue in your code You can use the below code

int x=0;
foreach (GridViewRow row in dgridTransactions.Rows)
{
    if(x<100 )
    {
        var oneTransaction = (CheckBox)row.FindControl("chkAssigned");
        oneTransaction.Checked = true;
    }
    else
        break;
    x++;
}

The foreach (GridViewRow row in dgridTransactions.Rows) loop runs for each row in your grid.

and in that you are using for (int x = 0; x <=100;x++ ){ which runs 100 times for every row.

You can use jquery or javascript for this Here is a JSFiddle which can help you

Upvotes: 0

Bizniztime
Bizniztime

Reputation: 1036

If you want to run first hundred rows you only need this loop

for(int x = 0; x < 100; x++)
{
    GridViewRow row = dgridTransactions.Rows[x];
    // then manage row properties
    CheckBox cb = (CheckBox)row.FindControl("chkAssigned");
    cb.Checked = true;
}

Upvotes: 1

Related Questions