C# DataTable转ListView显示
Posted New_HackerHK
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# DataTable转ListView显示相关的知识,希望对你有一定的参考价值。
### 封装方法
```C#
/// <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) { }
}
//网络素材仅限收藏 方便学习
以上是关于C# DataTable转ListView显示的主要内容,如果未能解决你的问题,请参考以下文章
C# Winform 关于ListView控件绑定DataTable