首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# WinForms ListView 顯示資料庫記錄完整範例 (OleDb + Access)

     編輯:關於C#

ListView 控制項在 View.Details 模式下可呈現類似試算表的多欄資料,適合顯示資料庫記錄。本文示範使用 OleDb 連接 Access 資料庫,手動將 OleDbDataReader 逐筆轉為 ListViewItem 並加入欄位。

完整程式碼 (Program.cs)

using System;
using System.Data.OleDb;
using System.Drawing;
using System.Windows.Forms;

public class MainForm : Form
{
    private readonly ListView _lv = new ListView();
    private readonly OleDbConnection _conn;

    public MainForm()
    {
        // 連線字串:專案目錄下的 MY.MDB
        string connStr = $@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={Application.StartupPath}\MY.MDB";
        _conn = new OleDbConnection(connStr);

        InitializeListView();
        LoadData();
        SetupForm();
    }

    private void InitializeListView()
    {
        _lv.Dock = DockStyle.Fill;
        _lv.View = View.Details;
        _lv.FullRowSelect = true;
        _lv.GridLines = true;
        _lv.MultiSelect = false;
        _lv.HeaderStyle = ColumnHeaderStyle.Nonclickable;
        _lv.Scrollable = true;

        // 欄位對應資料庫欄位
        _lv.Columns.Add("姓名", 60, HorizontalAlignment.Right);
        _lv.Columns.Add("住宅電話", 100, HorizontalAlignment.Left);
        _lv.Columns.Add("辦公電話", 100, HorizontalAlignment.Left);
        _lv.Columns.Add("行動電話", 100, HorizontalAlignment.Left);
        _lv.Columns.Add("居住地點", 100, HorizontalAlignment.Left);
        _lv.Columns.Add("工作單位", 100, HorizontalAlignment.Left);
        _lv.Columns.Add("電子郵件", 100, HorizontalAlignment.Left);

        Controls.Add(_lv);
    }

    private void LoadData()
    {
        try
        {
            _conn.Open();
            using (var cmd = new OleDbCommand("SELECT * FROM Persons", _conn))
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var item = new ListViewItem(reader["Name"].ToString());
                    item.SubItems.Add(reader["HomePhone"].ToString());
                    item.SubItems.Add(reader["WorkPhone"].ToString());
                    item.SubItems.Add(reader["MobilePhone"].ToString());
                    item.SubItems.Add(reader["City"].ToString());
                    item.SubItems.Add(reader["Address"].ToString());
                    item.SubItems.Add(reader["Email"].ToString());
                    _lv.Items.Add(item);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("載入失敗:" + ex.Message);
        }
        finally
        {
            if (_conn.State == System.Data.ConnectionState.Open)
                _conn.Close();
        }
    }

    private void SetupForm()
    {
        Text = "ListView 顯示資料庫記錄";
        ClientSize = new Size(700, 400);
        FormClosed += (s, e) =>
        {
            if (_conn.State == System.Data.ConnectionState.Open)
                _conn.Close();
        };
    }

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

資料庫準備 (Access MY.MDB)

建立資料表 Persons,欄位如下:

欄位名型別說明
NameText (50)姓名
HomePhoneText (20)住宅電話
WorkPhoneText (20)辦公電話
MobilePhoneText (20)行動電話
CityText (50)居住城市
AddressText (100)詳細地址
EmailText (100)電子郵件

插入幾筆測試資料後,將 MY.MDB 放在編譯輸出目錄 (bin\Debug) 或專案根目錄。

關鍵技術點解析

技術點說明
View.Details啟用多欄列表模式,需搭配 Columns 設定
FullRowSelect = true整行反白,而非僅第一欄
GridLines = true顯示格線,增強可讀性
ListViewItem.SubItems第 0 項為主項 (對應第一欄),其餘為 SubItems
OleDbDataReader.Read()前進一筆,回傳 false 表示無資料
連線關閉在 FormClosed 事件確保釋放

改用 SQL Server / PostgreSQL / MySQL

僅需更換連線字串與對應的 ADO.NET Provider:

// SQL Server (System.Data.SqlClient / Microsoft.Data.SqlClient)
string connStr = "Server=.;Database=MyDb;User Id=sa;Password=123;TrustServerCertificate=True;";

// PostgreSQL (Npgsql)
string connStr = "Host=localhost;Database=mydb;Username=postgres;Password=123;";

// MySQL (MySql.Data)
string connStr = "Server=localhost;Database=mydb;Uid=root;Pwd=123;";

其餘 ListView 填充邏輯完全相同,展現 ADO.NET 介面一致性優勢。

效能優化建議

  • 大量資料 (超過 1000 筆) 建議啟用虛擬模式 _lv.VirtualMode = true,實作 RetrieveVirtualItem 事件按需載入。
  • 使用 _lv.BeginUpdate() / _lv.EndUpdate() 包裹批次新增,避免重繪閃爍。
  • 考慮改用 DataGridView 內建資料繫結 (DataSource = dataTable) 簡化程式碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved