1

我有一个从包含 100 行或更多行的 XML 文件加载的数据集,但我一次只能将十五行(要求)显示到 DataGridView 中。没有用户交互;一个 10 秒的计时器移动到接下来的 15 行。

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> 
4

1 回答 1

0

我认为您的解决方案可以使用一个简单的 LINQ 查询来解决,每 10 秒显示一页 15 条记录:

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();
}
于 2012-04-15T02:08:19.053 回答