2012-04-14 36 views
1

我有一個DataSet從一個具有100或更多行的XML文件中加載,但我一次只能向DataGridView顯示15行(需求)。沒有用戶交互;十秒計時器移動到接下來的十五行。分頁綁定到DataSet的DataGridView?

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文件

<?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> 
+0

在這看看[示例](http://www.codeproject.com/Articles/211551/A-Simple-way-for-Paging-in-DataGridView-in-WinForm) – 2012-04-14 13:39:29

回答

0

我認爲您的解決方案可以用一個簡單的LINQ查詢,顯示的15條記錄每10秒一個頁面來解決:

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

這裏的其餘使上述方法工作的代碼:

假設這些變量在Form類中:

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 

我會讀你的XML幾乎相同,但不同的數據發送到您的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(); 

這裏的計時器滴答方法:

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(); 
}