Net Core教程

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

本文主要是介绍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);
            }
        }

这篇关于c#listview控件的数据添加和常用事件的处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!