.NET-一种实现表格数据滚动显示的方法,每隔一定时间,计时器刷新回调函数,移除第一行元素,然后插入最后一行。由于是链表实现的,算法时间复杂度控制在O(1)。
private void scrollGridTimer_Tick(object sender, EventArgs e)
{
int rowcnt = grid.Rows.Count;
if (rowcnt == 0) return;
DataTable data = grid.DataSource as DataTable;
object[] rowdata = data.Rows[0].ItemArray;
data.Rows.RemoveAt(0);
var newrow = data.NewRow();
newrow.ItemArray = rowdata;
data.Rows.InsertAt(newrow,rowcnt-1);
}
注意以下方法,是不行的,RemoveAt后,firstrow虽然表结构还在,但是数据已经清空。
int rowcnt = uprUoeGrid.Rows.Count;
if (rowcnt == 0) return;
DataTable data = grid.DataSource as DataTable;
DataRow firstrow = data.Rows[0];
data.Rows.RemoveAt(0);
data.Rows.InsertAt(firstrow,rowcnt-1);
ImportRow方法也失效,表现出来的现象是并未插入到表格中。
private void scrollGridTimer_Tick(object sender, EventArgs e)
{
int rowcnt = grid.Rows.Count;
if (rowcnt == 0) return;
DataTable data = grid.DataSource as DataTable;
object[] rowdata = data.Rows[0].ItemArray;
data.Rows.RemoveAt(0);
var newrow = data.NewRow();
newrow.ItemArray = rowdata;
data.ImportRow(newrow);
}
查下这个原因,msdn上说:
Calling NewRow adds a row to the table using the existing table schema, but with default values for the row, and sets the DataRowState to Detached. Calling ImportRow preserves the existing DataRowState along with other values in the row. If the DataRow that is passed as a parameter is in a detached state, it is ignored, and no exception is thrown.
private void scrollGridTimer_Tick(object sender, EventArgs e)
{
int rowcnt = grid.Rows.Count;
if (rowcnt == 0) return;
DataTable data = grid.DataSource as DataTable;
DataRow row = data.Rows[0];
data.ImportRow(row);
data.Rows.RemoveAt(0);
}
上面代码NewRow后,newrow处于detached状态,此时是不允许ImportRow,所以失败了。
一共19行,滚动实现的效果图如下: