简体   繁体   中英

Paging a DataGridView bound to a DataSet?

I have a DataSet loaded from an XML file with 100 or more rows but I can only display fifteen rows (requirement) into a DataGridView at a time. There is no user interaction; a ten second timer moves to the next fifteen rows.

FileStream stream = new FileStream("file.xml", FileMode.Open); 
ds.readXml(stream); 
Stream.Close(); 
datagridview1.DataSource = ds.Tables[0]; 
ds.Tables[0].DefaultView.Sort = "start asc"; 

XML file

<?xml version="1.0" standalone="yes"?> 
<Table> 
  <hours> 
    <Start>10:00 AM</Start> 
    </hours> 
<hours> 
    <Start>11:00 AM</Start> 
    </hours> 
<hours> 
    <Start>1:00 PM</Start> 
    </hours> 
<hours> 
    <Start>2:00 PM</Start> 
    </hours> 
</Table> 

I think your solution could be solved using a simple LINQ query to show a page of 15 records every 10 seconds:

private void BindPageToGrid()
{
    var dsPage = _ds.Tables[0].AsEnumerable()
        .Skip(_nPage * PAGE_SIZE)
        .Take(PAGE_SIZE)
        .Select(x => x);
    datagridview1.DataSource = dsPage.CopyToDataTable<DataRow>();
}

Here's the rest of the code that makes the above method work:

Assume these variables are in your Form class:

const int PAGE_SIZE = 15; // the number of total items per page
private DataSet _ds;      // the XML data you read in
private  int _nPage;      // the current page to display
private int _maxPages;    // the max number of pages there are

I would read in your XML nearly the same, but send different data to your DataGridView:

FileStream stream = new FileStream("file.xml", FileMode.Open);
_ds.ReadXml(stream);
stream.Close();
_ds.Tables[0].DefaultView.Sort = "start asc";

// determine how many pages we need to show the data
_maxPages = Convert.ToInt32(Math.Ceiling(
               (double)_ds.Tables[0].Rows.Count / PAGE_SIZE));

// start on the first page
_nPage = 0;
// show a page of data in the grid
BindPageToGrid();
// increment to the next page, but rollover to first page when finished
_nPage = (_nPage + 1) % _maxPages;

// start the 10-second timer
timer1.Interval = (int)new TimeSpan(0, 0, 10).TotalMilliseconds;
timer1.Tick += timer1_Tick;
timer1.Start();

Here's the timer tick method:

void timer1_Tick(object sender, EventArgs e)
{
    timer1.Stop();
    // show a page of data in the grid
    BindPageToGrid();
    // increment to the next page, but rollover to first page when finished
    _nPage = (_nPage + 1) % _maxPages;
    timer1.Start();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM