c#listview控件的数据添加和常用事件的处理

设置表格线:

FullRowSelect=true;

GridLines=true;

View=Details;

用数据表添加数据:

     /// <summary>
            /// ListView控件内容显示
            /// </summary>
            /// <param name="dt">数据表源</param>
            /// <param name="liv">控件名称</param>
            public static void LivMainDisPlay(DataTable dt, ListView liv)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListViewItem list = new ListViewItem();
                    for (int j = 0; j < dt.Columns.Count - 1; j++)
                    {
                        list.SubItems[0].Text = dt.Rows[i][0].ToString();
                        list.SubItems.Add(dt.Rows[i][j + 1].ToString());
                    }
                    liv.Items.Add(list);
                }
            }
            /// <summary>
            /// ListView控件列名显示
            /// </summary>
            /// <param name="dt">数据表源</param>
            /// <param name="liv">控件名称</param>
            public static void LivColumnDisplay(DataTable dt, ListView liv)
            {
                foreach (DataColumn i in dt.Columns)
                {
                    liv.Columns.Add(i.ColumnName);
                }
                liv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            }

调用顺序如下:

listview1.Clear();

LivMainDisPlay(dt,listview1);

LivColumnDisplay(dt,listview1);

设置表格鼠标移动背景改变:

    private void lst_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
            {
                foreach (ListViewItem item in this.lst.Items)
                {
                    if(e.Item!=item)
                    item.BackColor = Color.White;
                }
                e.Item.BackColor = Color.Red;
               
            }

单击某行复制选中文本(复制到系统剪切板):

private void lst_Click(object sender, EventArgs e)
        {
            int selectCount = lst.SelectedItems.Count;
            if (selectCount > 0)

            {

System.Windows.Forms.Clipboard.SetText(lst.SelectedItems[0].SubItems[0].Text);
            }
        }

上一篇:2021年Android高级面试题,讲的明明白白!


下一篇:史上最全的Android面试题集锦,大厂面试题汇总