using System ;
using System.Windows.Forms ;
using System.Drawing ;
using System.Data ;
using System.Data.OleDb ;
class MainForm : Form
{ // 定義數據連接的字符串
private static string strConnect = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " +
Application.StartupPath + "\\MY.MDB" ;
private OleDbConnection conConnection = new OleDbConnection ( strConnect ) ;
private ListView lv ;
public MainForm ( )
{
// 初始化Form
this.Left = 0 ;
this.Top = 0 ;
this.Text = "在ListView中顯示數據庫內容!" ;
// 初始化ListView
lv = new ListView ( ) ;
lv.Left = 0 ;
lv.Top = 0 ;
lv.Width = 700 ;
lv.Height = this.ClientRectangle.Height ;
lv.GridLines = true ; file://顯示各個記錄的分隔線
lv.FullRowSelect = true ; file://要選擇就是一行
lv.View = View.Details ; file://定義列表顯示的方式
lv.Scrollable = true ; file://需要時候顯示滾動條
lv.MultiSelect = false ; // 不可以多行選擇
lv.HeaderStyle = ColumnHeaderStyle.Nonclickable ;
// 針對數據庫的字段名稱,建立與之適應顯示表頭
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 ) ;
lv.Visible = true ;
OleDbDataReader reader ;
string strCommand = "SELECT * FROM Persons" ;
this.conConnection.Open ( ) ;// 打開數據連接
OleDbCommand cmd = new OleDbCommand ( strCommand , conConnection ) ;
reader = cmd.ExecuteReader ( ) ;//獲得數據集
// 不斷往列表中添加數據記錄
while ( reader.Read ( ) )
{
ListViewItem li = new ListViewItem ( ) ;
li.SubItems.Clear ( ) ;
li.SubItems[0].Text = reader["name"].ToString ( ) ;
li.SubItems.Add ( reader["HomePhone"].ToString ( ) ) ;
li.SubItems.Add ( reader["WorkPhone"].ToString ( ) ) ;
li.SubItems.Add ( reader["MobilePhone"].ToString ( ) ) ;
li.SubItems.Add ( reader["City"].ToString ( ) ) ;
li.SubItems.Add ( reader["Address"].ToString ( ) ) ;
li.SubItems.Add ( reader["Email"].ToString ( ) ) ;
lv.Items.Add ( li ) ;
}
reader.Close ( ) ; // 關閉數據集
// 在Form中添加此列表
this.Controls.Add ( lv ) ;
// 關閉Form的時候,同時也關閉數據連接
this.Closed+=new EventHandler ( this_Closed ) ;
}
protected void this_Closed ( object sender , EventArgs eArgs )
{
this.conConnection.Close ( ) ; file://關閉數據連接
}
public static void Main ( )
{
Application.Run ( new MainForm ( ) ) ;
}
}
|
在成功編譯了上面源程序代碼以后,在同一目錄下建立一個Acess 2000的數據庫,命名為MY.MDB,然后在其中建立一張數據表,字段如下:name,HomePhone,WorkPhone,MobilePhone,City,Address,Email。此時運行編譯后的程序就可以得到如下運行界面:

圖01:用ListView顯示數據記錄 |