ListView控件显示日志每次刷新只显示30条数据
功能: 实时记录接收数据,用listview控件显示出来,保持数据一直是30条
1.将信息显示到控件。
/// <summary> /// 在ListView控件里显示日志信息 /// </summary> public class CustomListViewDisplayNews { /// <summary> /// 委托控件显示数据 /// </summary> /// <param name="list">控件</param> /// <param name="index">序号</param> /// <param name="code">第一个值</param> /// <param name="data">第二个值</param> /// <param name="time">时间</param> public delegate void DisplayNews(ListView list, double index,string code, string data,string time); /// <summary> /// 显示的信息数 /// </summary> public static int Num_Record = 0; private void ListView_DisplayNews(ListView list, double iIndex,string Code,string Data,string Time) { if (list.InvokeRequired == false) { ListViewItem lvi = new ListViewItem(); lvi.SubItems[0].Text = iIndex.ToString(); lvi.SubItems.Add(Code); lvi.SubItems.Add(Data); lvi.SubItems.Add(Time); list.Items.Insert(0, lvi); for (int i = 0; i < list.Columns.Count; i++) { list.Columns[i].Width = -2; } } else { //通过使用Invoke的方法,让子线程告诉窗体线程来完成相应的控件操作 DisplayNews degete = new DisplayNews(ListView_DisplayNews); //使用控件lstMain的Invoke方法执行DMSGD代理(其类型是DispMSGDelegate) list.Invoke(degete, (object)iIndex, (object)Code, (object)Data, (object)Time); } } /// <summary> /// 调函数显示list信息 /// </summary> /// <param name="list">容器</param> /// <param name="result">值</param> /// <param name="value">值</param> public void listView_DisplayNews(ListView list, object value,object result) { DisplayNews dis = new DisplayNews(ListView_DisplayNews); string Read_Value = (string)value; string Read_Result = (string)result; Num_Record++; ListView_DisplayNews(list, Num_Record, Read_Value,Read_Result, DateTime.Now.ToString()); } }
1.1调用函数显示日志
CustomListViewDisplayNews list = new CustomListViewDisplayNews(); list.listView_DisplayNews(listView1, "NG", "NoRead");
2.保持数据显示一直是30条。
思路:控件显示数据可分为头数据和尾数据,如第1条显示数据为头数据,第30是尾数据。当增加到31条数据时,把头数据删掉,序号不变。
当控件大于30条数据时,每刷新一条都执行一遍删除头数据的代码
if (CustomListViewDisplayNews.Num_Record > 30) { RefreshListview(); }
private void RefreshListview() { int nRowOrder = 0; int nRowOrders = listView1.Items.Count;//行数 for (nRowOrder = 0; nRowOrder < nRowOrders; nRowOrder++) { var row = nRowOrders - 1; if (nRowOrder == row) { listView1.Items.RemoveAt(row); } } }
更简易的代码可以这样写
if (CustomListViewDisplayNews.Num_Record > 30) { listView1.Items.RemoveAt(30); }