C# DataTable转ListView显示

封装方法

/// <summary>
/// DataTable转ListView
/// </summary>
/// <param name="lv"></param>
/// <param name="dt"></param>
public static void DataTableToListView(System.Windows.Forms.ListView lv, System.Data.DataTable dt)
{
    try
    {
        if (dt != null)
        {
            lv.View = System.Windows.Forms.View.Details;
            lv.FullRowSelect = true;
            lv.BeginUpdate();
            lv.Clear();
            lv.View = System.Windows.Forms.View.Details;
            lv.AllowColumnReorder = true;
            lv.GridLines = true;
            lv.Items.Clear();
            lv.Columns.Clear();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                lv.Columns.Add(dt.Columns[i].Caption.ToString(), dt.Columns[i].Caption.Trim().Length * 20, System.Windows.Forms.HorizontalAlignment.Left);
            }
            foreach (System.Data.DataRow dr in dt.Rows)
            {
                System.Windows.Forms.ListViewItem lvi = new System.Windows.Forms.ListViewItem(dr[0].ToString());
                for (int j = 1; j < dt.Columns.Count; j++)
                {
                    lvi.SubItems.Add(dr[j].ToString());
                }
                lv.Items.Add(lvi);
            }
            lv.AutoResizeColumns(System.Windows.Forms.ColumnHeaderAutoResizeStyle.HeaderSize);
            lv.EndUpdate();
        }
    }
    catch (Exception ex) {  }
}

//网络素材仅限收藏 方便学习

posted @ 2021-06-07 16:59  New_HackerHK  阅读(321)  评论(0编辑  收藏  举报