darby
darby

Reputation: 167

Split datagridview after certain amount of rows

I have a datagridview that looks like this:

┌───────────┬───────────┐
│ ID        │ Name      │
├───────────┼───────────┤
│ 1         │ Jack      │
│ 2         │ Carl      │
│ 3         │ Daniel    │
│ 4         │ Abby      │
│ ..        │           │
│ 10000     │           │
└───────────┴───────────┘

With a column ID and Name the ID column has more than 10.000 ID's in it how can I do it that if I click on a button a messagebox will pop up but with only the first 999 ID's and if I go and click ok it will show me the next 999 ID's till it's finished?

Upvotes: 0

Views: 375

Answers (1)

Mitarano
Mitarano

Reputation: 30

First divide the Rows in your DataGridView into parts of the size you need. When the user clicks the button you can iterate over and build an output string for each part.

private IEnumerable<IEnumerable<DataGridViewRow>> SplitDataGridView(DataGridView dgv)
{
    var rows = new List<DataGridViewRow>(size);

    foreach (DataGridViewRow row in dgv.Rows)
    {
        rows.Add(row);

        if (rows.Count == size)
        {
            yield return rows;
            rows = new List<DataGridViewRow>(size);
        }
    }

    if (rows.Count > 0)
    {
        yield return rows;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    foreach (var rows in SplitDataGridView(dataGridView))
    {
        var sb = new StringBuilder();
        foreach (var row in rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                sb.Append(cell.Value);
                sb.Append(delimiter);
            }
            sb.Remove(sb.Length - delimiter.Length, delimiter.Length);
            sb.AppendLine();
        }

        MessageBox.Show(sb.ToString());
    }
}

Upvotes: 1

Related Questions