首页 >> VS.NET

c# listview 使用方法

2012-06-28 14:39:09

c#的ListView是Windows应用程序中经常用到;
这里是其一个比较简单的用法;
其中: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;
}

}