vb.net中datatable和listwive怎轉換
时间: 2023-11-11 09:08:04 浏览: 156
可以使用以下代码实现datatable和listview之间的转换:
// 将datatable转换为listview
public static void DataTableToListView(DataTable table, ListView listView)
{
listView.Clear();
// 添加列
foreach (DataColumn column in table.Columns)
{
listView.Columns.Add(column.ColumnName, -2, HorizontalAlignment.Left);
}
// 添加行
foreach (DataRow row in table.Rows)
{
ListViewItem item = new ListViewItem(row[0].ToString());
for (int i = 1; i < table.Columns.Count; i++)
{
item.SubItems.Add(row[i].ToString());
}
listView.Items.Add(item);
}
}
// 将listview转换为datatable
public static DataTable ListViewToDataTable(ListView listView)
{
DataTable table = new DataTable();
// 添加列
foreach (ColumnHeader header in listView.Columns)
{
table.Columns.Add(header.Text);
}
// 添加行
foreach (ListViewItem item in listView.Items)
{
DataRow row = table.NewRow();
row[0] = item.Text;
for (int i = 1; i < item.SubItems.Count; i++)
{
row[i] = item.SubItems[i].Text;
}
table.Rows.Add(row);
}
return table;
}
阅读全文