這裏是其一個比較簡單的用法;
其中:ListView爲:eListView;
用法如下所示:
//程序初始設置其基本屬性,註釋如下,並用loadData()得到其顯示內容;
//設置eListView的基本屬性
//loadData()函數得到表項,並顯示
private void EmailForm_Load(object sender, System.EventArgs e)
{
eListView.GridLines = true ;//顯示各個記錄的分隔線
eListView.FullRowSelect = true ;//要選擇就是一行
eListView.View = View.Details ;//定義列表顯示的方式
eListView.Scrollable = true ;//需要時候顯示滾動條
eListView.MultiSelect = false ; // 不可以多行選擇
eListView.HeaderStyle = ColumnHeaderStyle.Clickable;
loadData();
}
//***********************得到數據集並綁定到rListView控件************/
//清空eListView
//設置表頭。
//執行數據庫查詢操作,得到表中所要顯示的數據
//數據按行綁定到eListView
/*********************************************************************/
private void loadData()
{
this.eListView.Clear();
// 針對數據庫的字段名稱,建立與之適應顯示錶頭
eListView.Columns.Add ( "序號" , 50, HorizontalAlignment.Center ) ;
eListView.Columns.Add ( "用戶名" , 60 , HorizontalAlignment.Center ) ;
eListView.Columns.Add ( "郵件地址" , 150 , HorizontalAlignment.Center ) ;
eListView.Visible = true ;
string strSql = string.Format("select name,mailbox from mail ");
DBConnection dbcon = new DBConnection();
IDataReader read = dbcon.getRead(strSql);
int i =0;
while(read.Read())
{
i ++;
ListViewItem Item = new ListViewItem ( ) ;
Item.SubItems.Clear ( ) ;
Item.SubItems[0].Text = i.ToString() ;
Item.SubItems.Add ( read.GetString(0)) ;
Item.SubItems.Add ( read.GetString(1)) ;
eListView.Items.Add ( Item ) ;
}
dbcon.close();//關閉數據庫鏈接
}
通過以上就可以得到相應的數據,並顯示到ListView中;
以下函數是對ListView雙擊取數據的一個例子:
//依據事件索引和對應的列數,把相關的內容對應的顯示在相關TextBox控件中
private void eListView_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(this.eListView.SelectedItems.Count >0)
{
this.tbName.Text = eListView.SelectedItems[0].SubItems[1].Text;
this.tbEmail.Text = eListView.SelectedItems[0].SubItems[2].Text;
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _8_07
{
public partial class frmListView : Form
{
public frmListView()
{
InitializeComponent();
}
private void frmListView_Load(object sender, EventArgs e)
{
}
private void bntDelete_Click(object sender, EventArgs e)
{
lvStudent.Items.Clear();
}
private void bntAdd_Click(object sender, EventArgs e)
{
this.lvStudent.View = View.Details;
this.lvStudent.FullRowSelect = true;
SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=zhy");
con.Open();
SqlCommand com = new SqlCommand("select * from student", con);
SqlDataReader dr = com.ExecuteReader();
this.lvStudent.Items.Clear();
while (dr.Read())
{
ListViewItem lt = new ListViewItem(dr.GetValue(0).ToString());
lt.SubItems.Add(dr.GetValue(1).ToString());
lt.SubItems.Add(dr.GetValue(2).ToString());
this.lvStudent.Items.Add(lt);
}
dr.Close();
con.Close();
this.lvStudent.Alignment = ListViewAlignment.SnapToGrid;
this.lvStudent.GridLines = true;
}
private void bntEsce_Click(object sender, EventArgs e)
{
Application.Exit();
}