最近在做一个WPF小项目,因为需要处理一些数据,迫不得已写了一个函数,算是一个小算法吧,在此写出以便温故知新,同时希望牛人不吝赐教,点出其中不足之处。
简化需求:
创建一个datatable表dt,dt表中的记录行数是变量m。创建datatable表dt1、dt2,dt1和dt2循环显示dt中的数据,添加一个计时器定时刷新dt1、dt2中的数据,且dt1和dt2每次只能显示n行。
1、声明变量
PRivate DispatcherTimer timer; DataTable dt = new DataTable(); DataTable dt1 = new DataTable(); DataTable dt2 = new DataTable(); public static int currentRows = 0;//当前行 public static int currentRows2 = 0;//中间变量
定时器:
timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 5); timer.Tick += new EventHandler(timer_Tick); timer.Start();
2、添加控件,此处添加两个datagrid控件(用以显示dt1和dt2中的数据)
<DataGrid AutoGenerateColumns="False" Height="335" HorizontalAlignment="Left" Margin="220,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" > <DataGrid.Columns > <DataGridTextColumn Header="id" Binding="{Binding Path=id}"></DataGridTextColumn> <DataGridTextColumn Header="name" Binding="{Binding Path=name}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid> <DataGrid AutoGenerateColumns="False" Height="305" HorizontalAlignment="Left" Margin="463,31,0,0" Name="dataGrid2" VerticalAlignment="Top" Width="200" > <DataGrid.Columns > <DataGridTextColumn Header="id" Binding="{Binding Path=id}"></DataGridTextColumn> <DataGridTextColumn Header="name" Binding="{Binding Path=name}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid>
3、创建datatable表dt,并且初始化dt1和dt2
private void Initialize(int num) { dt.Columns.Add(new DataColumn("id", typeof(int))); dt.Columns.Add(new DataColumn("name", typeof(string))); for (int i = 0; i < num; i++) { DataRow dr = dt.NewRow(); dr["id"] = i; dr["name"] = "tom" + i.ToString(); dt.Rows.Add(dr); } dt1.Columns.Add(new DataColumn("id", typeof(int))); dt1.Columns.Add(new DataColumn("name", typeof(string))); dt2.Columns.Add(new DataColumn("id", typeof(int))); dt2.Columns.Add(new DataColumn("name", typeof(string))); }
初始化时调用:
Initialize(11);
4、编写函数
public void Update(int num) { int rows = dt.Rows.Count; int num1 = 0; int num2 = 0; currentRows = currentRows2; for (int i = currentRows; i < (currentRows + num); i++) { num1++; currentRows2++; DataRow dr = dt1.NewRow(); dr["id"] = Convert.ToInt32(dt.Rows[i][0].ToString()); dr["name"] = dt.Rows[i][1].ToString(); dt1.Rows.Add(dr); if (i == rows - 1) { i = -1; currentRows2 = 0; } if (num1 == num) { break; } } currentRows = currentRows2; for (int i = currentRows; i < (currentRows + num); i++) { num2++; currentRows2++; DataRow dr = dt2.NewRow(); dr["id"] = Convert.ToInt32(dt.Rows[i][0].ToString()); dr["name"] = dt.Rows[i][1].ToString(); dt2.Rows.Add(dr); if (i == rows - 1) { i = -1; currentRows2 = 0; } if (num2 == num) { break; } } }
5、定时刷新dt1和dt2中的数据
void timer_Tick(object sender, EventArgs e) { dt1.Clear(); dt2.Clear(); Update(3); }
新闻热点
疑难解答