• C# Listview的运用汇总(winform)


    以下是我了解到Listview的几个知识点

    1.创建表头
    #region 给listview加表头:
    
                lvList.Columns.AddRange(new ColumnHeader[] { 
                    new ColumnHeader(){ Name="Mac",Text="Mac",Width=100},
                    new ColumnHeader(){ Name="Ip",Text="Ip地址",Width=100},
                    new ColumnHeader(){ Name="Port",Text="Port",Width=100},
                    new ColumnHeader(){ Name="Protocol",Text="Protocol",Width=100},
                    new ColumnHeader(){ Name="PackId",Text="AccessTime",Width=100},
                    new ColumnHeader(){ Name="AccessTime",Text="AccessTime",Width=100},
                });
    
                //选中一行
                lvList.FullRowSelect = true;
                #endregion
    2.把数据绑定到listview上
    View Code 
    
                    #region 把序列化后的数据显示到listview上:
                    lvList.Items.Clear();
                    foreach (CustomerServ result in rd.Results)
                    {
    
                        var lvi = new ListViewItem(result.Mac);
                        lvi.SubItems.Add(result.Ip);
                        lvi.SubItems.Add(result.Port.ToString());
                        lvi.SubItems.Add(result.Protocol);
                        lvi.SubItems.Add(result.PackId.ToString());
                        lvi.SubItems.Add(result.AccessTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        lvList.Items.Add(lvi);
                    }
                    var c = 0;
                    #endregion
    3.读取行数据
    #region 单击行读取行数据:
    
                if (this.lvList.SelectedItems.Count > 0)
                {
                    txtClient.Text = this.lvList.SelectedItems[0].SubItems[0].Text;
                    txtIP.Text = this.lvList.SelectedItems[0].SubItems[1].Text;
                    txtPort.Text = this.lvList.SelectedItems[0].SubItems[2].Text;
                    txtProtocol.Text = this.lvList.SelectedItems[0].SubItems[3].Text;
                    txtPackId.Text = this.lvList.SelectedItems[0].SubItems[4].Text;
                    txtAccessTime.Text = this.lvList.SelectedItems[0].SubItems[5].Text;
                }
    
                #endregion
    4.遍历删除listview中checkbox被选中的记录
    View Code 
    
     /// <summary>
            /// 删除选中行
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnDelete_Click(object sender, EventArgs e)
            {
    
                foreach (ListViewItem  item in this.lvList.CheckedItems)
                {
                    this.lvList.Items.RemoveAt(item.Index);
                }
    
            }
    5.根据某些字段模糊查询listview列表相关信息
    private void btnSelectA_Click(object sender, EventArgs e)
            {
                string _Mac = this.txtMac.Text;
                string _IP = this.txtIP.Text;
                lvList.Items.Clear();
                foreach (CustomerServ result in a.Results)
                {
                    if (_Mac.Trim().Length < 1 && _IP.Trim().Length < 1)
                    {
                        var lvi = new ListViewItem(result.Mac);
                        lvi.SubItems.Add(result.Ip);
    
                        lvi.SubItems.Add(result.Port.ToString());
                        lvi.SubItems.Add(result.Protocol);
                        lvi.SubItems.Add(result.PackId.ToString());
                        lvi.SubItems.Add(result.AccessTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        lvList.Items.Add(lvi);
                    }
                    else
                    {
                        if(Convert.ToInt32(result.Mac.IndexOf(_Mac,0))==0)
                        {
                            if (Convert.ToInt32(result.Ip.IndexOf(_IP, 0)) == 0)
                            {
                                var lvi = new ListViewItem(result.Mac);
                                lvi.SubItems.Add(result.Ip);
                                lvi.SubItems.Add(result.Port.ToString());
                                lvi.SubItems.Add(result.Protocol);
                                lvi.SubItems.Add(result.PackId.ToString());
                                lvi.SubItems.Add(result.AccessTime.ToString("yyyy-MM-dd HH:mm:ss"));
                                lvList.Items.Add(lvi);
                            }                      
                        }
                    }               
                }
            }
    6.checkbox的checked为true行变红,false时黑色
    View Code 
    
     private void lvList_ItemChecked(object sender, ItemCheckedEventArgs e)
            {
                ListViewItem MyItem = lvList.Items[e.Item.Index];
    
                foreach (ListViewItem item in this.lvList.Items)
                {
                    if (MyItem.Checked)
                    {
                        MyItem.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {
                        MyItem.ForeColor = System.Drawing.Color.Black;
                    }
                }
            }
    7.遍历listview,把上面的数据存到list中
    View Code 
    
     List<CustomerServ> m_CustomerServList = new List<CustomerServ>();
                foreach (ListViewItem item in lvList.Items)
                {
                    m_CustomerServList.Add(new CustomerServ()
                    {
                        Mac = item.SubItems[0].Text,
                        Ip = item.SubItems[1].Text,
                        Port = item.SubItems[2].Text,
                        Protocol = item.SubItems[3].Text,
                        PackId = Convert.ToInt32(item.SubItems[4].Text),
                        AccessTime = Convert.ToDateTime(item.SubItems[5].Text)
                    });
                }
    8.listview根据列名自动调整列宽
     lvList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
    9.listview列排序
    View Code 
    
    //使用 IComparer接口。
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    using System.Windows.Forms;
    
    namespace EtcommTest
    {
            class ListViewColumnSorter : IComparer
            {
                private int ColumnToSort;// 指定按照哪个列排序      
                private SortOrder OrderOfSort;// 指定排序的方式               
                private CaseInsensitiveComparer ObjectCompare;// 声明CaseInsensitiveComparer类对象,
                public ListViewColumnSorter()// 构造函数
                {
                    ColumnToSort = 0;// 默认按第一列排序            
                    OrderOfSort = SortOrder.None;// 排序方式为不排序            
                    ObjectCompare = new CaseInsensitiveComparer();// 初始化CaseInsensitiveComparer类对象
                }
                // 重写IComparer接口.        
                // <returns>比较的结果.如果相等返回0,如果x大于y返回1,如果x小于y返回-1</returns>
                public int Compare(object x, object y)
                {
                    int compareResult;
                    ListViewItem listviewX, listviewY;
                    // 将比较对象转换为ListViewItem对象
                    listviewX = (ListViewItem)x;
                    listviewY = (ListViewItem)y;
                    // 比较
                    compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
                    // 根据上面的比较结果返回正确的比较结果
                    if (OrderOfSort == SortOrder.Ascending)
                    {   // 因为是正序排序,所以直接返回结果
                        return compareResult;
                    }
                    else if (OrderOfSort == SortOrder.Descending)
                    {  // 如果是反序排序,所以要取负值再返回
                        return (-compareResult);
                    }
                    else
                    {
                        // 如果相等返回0
                        return 0;
                    }
                }
                /// 获取或设置按照哪一列排序.        
                public int SortColumn
                {
                    set
                    {
                        ColumnToSort = value;
                    }
                    get
                    {
                        return ColumnToSort;
                    }
                }
                /// 获取或设置排序方式.    
                public SortOrder Order
                {
                    set
                    {
                        OrderOfSort = value;
                    }
                    get
                    {
                        return OrderOfSort;
                    }
                }
            }
    }
    ***********************************
       public Main()
            {
                InitializeComponent();
                // 创建一个ListView排序类的对象,并设置lvList的排序器
                lvwColumnSorter = new ListViewColumnSorter();
                this.lvList.ListViewItemSorter = lvwColumnSorter;
            }
            ListViewColumnSorter lvwColumnSorter;
      //单击列标头时触发
            private void lvList_ColumnClick(object sender, ColumnClickEventArgs e)
            {
                // 检查点击的列是不是现在的排序列.
                if (e.Column == lvwColumnSorter.SortColumn)
                {
                    // 重新设置此列的排序方法.
                    if (lvwColumnSorter.Order == SortOrder.Ascending)
                    {
                        lvwColumnSorter.Order = SortOrder.Descending;
                    }
                    else
                    {
                        lvwColumnSorter.Order = SortOrder.Ascending;
                    }
                }
                else
                {
                    // 设置排序列,默认为正向排序
                    lvwColumnSorter.SortColumn = e.Column;
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
                // 用新的排序方法对ListView排序
                this.lvList.Sort();           
            }
    10.让选中行失去焦点后仍然保持天蓝色
    View Code 
    
     /// <summary>
            /// listview的SelectedIndexChanged事件
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void lvList_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (lvList.FocusedItem != null)
                {
                    if (this.lvList.SelectedItems.Count > 0)
                    {
                        if (lvList.SelectedItems[0].BackColor == SystemColors.Highlight)
                        {
                            lvList.SelectedItems[0].BackColor = Color.White;
                            lvList.SelectedItems[0].ForeColor = Color.Black;
                            lvList.SelectedItems.Clear();
                        }
                        else
                        {
                            lvList.FocusedItem.BackColor = SystemColors.Highlight;
                            lvList.FocusedItem.ForeColor = Color.White;
                        }
                    }
                }
            }
    11.遍历listview把选中的用户生成一个字符串数组
    string[] str = new string[lvClients.CheckedItems.Count];
                    for (int i = 0; i < lvClients.CheckedItems.Count; i++)
                    {
                        str[i] = lvClients.CheckedItems[i].Text;
                    }
    12.listview分页
    View Code 
           private static int totalcount = 0;//记录数
            private static int pageIndex = 1;   //当前页 
            private static int pageSize = 10; //每页条数
            private static int pageCount = (totalcount / pageSize) + (totalcount % pageSize == 0 ? 0 : 1); //总页数
            public List<LogItem> Items;
               #region Listview分页:
    
            private void CalcPageStatus(List<LogItem> MyList, int pageSize, int pIndex)
            {
                totalcount = MyList.Count;
                pageCount = (totalcount / pageSize) + (totalcount % pageSize == 0 ? 0 : 1);
                pageIndex = pIndex;
    
                if (null == MyList)
                {
                    return;
                }
                var list = new List<LogItem>();
                //跳到首页
                if (pageIndex == 1)
                {
                    if (totalcount > pageSize)
                    {
                        for (int i = 0; i < pageSize; i++)
                        {
                            list.Add(MyList[i]);
                        }
                        if (pageCount == 1)
                        {
                            _tsbnextPage.Enabled = false;
                        }
                        else
                        {
                            _tsbnextPage.Enabled = true;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < totalcount; i++)
                        {
                            list.Add(MyList[i]);
                        }
                        _tsbnextPage.Enabled = false;
                    }
                    _tsbprevPage.Enabled = false;
                }
                //跳到尾页
                if (pageIndex >= pageCount && pageIndex > 1)
                {
                    int count = MyList.Count - (pageCount - 1) * pageSize;
                    for (int i = 0; i < count; i++)
                    {
                        list.Add(MyList[i + pageSize * (pageCount - 1)]);
                    }
                    if (pageIndex > 1)
                    {
                        _tsbprevPage.Enabled = true;
                    }
                    _tsbnextPage.Enabled = false;
                   
                }
                //跳到中间页
                if (pageIndex > 1 && pageIndex < pageCount)
                {
                    for (int i = 0; i < pageSize; i++)
                    {
                        list.Add(MyList[i + pageSize * (pageIndex - 1)]);
                    }
                    _tsbprevPage.Enabled = true;
                    _tsbnextPage.Enabled = true;
                }
                _tsplblMessage.Text = "  总页数:" + pageCount + "   每页显示:";
                FillLvLogs(list);
                TsbCPageAddItem();
                TsbCPageChange();
                Color();
            }
    
            /// <summary>
            /// 添加当前页的Item
            /// </summary>
            public void TsbCPageAddItem()
            {
                _tsbCPage.Items.Clear();
                for (int i = 0; i < pageCount; i++)
                {
                    _tsbCPage.Items.Add(1 + i);
                }
            }
    
            /// <summary>
            /// 判断当前页显示
            /// </summary>
            public void TsbCPageChange()
            {
                flage = false;
                TsbCPageAddItem();
                if (pageIndex == 1)
                {
                    _tsbCPage.SelectedIndex = pageIndex - 1;
                }
                if (pageIndex >= pageCount && pageIndex > 1)
                {
                    _tsbCPage.SelectedIndex = pageCount - 1;
                }
                if (pageIndex > 1 && pageIndex < pageCount)
                {
                    _tsbCPage.SelectedIndex = pageIndex - 1;
                }
                flage = true;
            }
    
    
            /// <summary>
            /// 首页
            /// </summary>
            public void LvHomePage()
            {
                if (totalcount > 0)
                {
                    CalcPageStatus(Items, pageSize, 1);
                }
            }
    
            /// <summary>
            /// 末页
            /// </summary>
            public void LvLastPage()
            {
                if (totalcount > 0)
                {
                    CalcPageStatus(Items, pageSize, pageCount);
                }
            }
    
            /// <summary>
            /// 上一页
            /// </summary>
            public void LvPageDown()
            {
                int index = Convert.ToInt32(_tsbCPage.Text) - 1;
                CalcPageStatus(Items, pageSize, index);
            }
    
            /// <summary>
            /// 下一页
            /// </summary>
            public void LvPageUp()
            {
                int index = Convert.ToInt32(_tsbCPage.Text) + 1;
                CalcPageStatus(Items, pageSize, index);
            }
    
    
            #endregion


     

  • 相关阅读:
    css知多少(10)——display
    css知多少(9)——float下篇
    centos-lynx
    linux-redis
    springMVC robots.txt 处理
    .net core
    docker快速入门+搭建javaweb环境
    maven+spring+springMVC+mybatis+dubbox
    微信群之社群经济的魔力
    maven项目部署打包
  • 原文地址:https://www.cnblogs.com/ybyi/p/2993088.html
Copyright © 2020-2023  润新知