安然不哭-西坝阿超个人博客

做技术一定要一颗恒心,这样才不会半途而废。

c#中listview与datatable的转换

2018-10-6 钟建超

using System.Collections.Generic; 
using System.Text; 
using System.Data; 
using System.Data.SqlClient; 
using System.Data.OleDb; 
using System.Windows.Forms; 
using System.Drawing; 


namespace ListViewFill 
{ 
    class ListViewFill 
    { 
        //fill the listview 
        static public void dataTableToListview(ListView lv, DataTable dt) 
        { 
            if (dt != null) 
            { 
                lv.Items.Clear(); 
                lv.Columns.Clear(); 
                for (int i = 0; i < dt.Columns.Count; i++) 
                { 
                    lv.Columns.Add(dt.Columns[i].Caption.ToString()); 
                } 
                foreach (DataRow dr in dt.Rows) 
                { 
                    ListViewItem lvi = new ListViewItem(); 
                    lvi.SubItems[0].Text = dr[0].ToString(); 


                    for (int i = 1; i < dt.Columns.Count; i++) 
                    { 
                        lvi.SubItems.Add(dr[i].ToString()); 
                    } 


                    lv.Items.Add(lvi); 
                } 
                lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); 
            } 
        } 
        static public void listViewToDataTable(ListView lv,DataTable dt) 
        { 
            int i, j; 
            DataRow dr; 
            dt.Clear(); 
            dt.Columns.Clear(); 
            //生成DataTable列头 
            for (i = 0; i < lv.Columns.Count; i++) 
            { 
                dt.Columns.Add(lv.Columns[i].Text.Trim(), typeof(String)); 
            } 
            //每行内容 
            for (i = 0; i < lv.Items.Count; i++) 
            { 
                dr = dt.NewRow(); 
                for (j = 0; j < lv.Columns.Count; j++) 
                { 
                    dr[j] = lv.Items[i].SubItems[j].Text.Trim(); 
                } 
                dt.Rows.Add(dr); 
            } 
        } 
    } 
}

标签: c#