1. 程式人生 > >使用ListView控件展示數據

使用ListView控件展示數據

菜單項 range edi 顏色 catalog 添加圖片 以及 const his

一.ImageList:存儲圖像集合

Images 存儲的所有圖像
ImageSize 圖像的大小
ColorDepth 顏色數
TransparentColor 被視為透明的顏色
先設置ColorDepth、ImageSize屬性值再添加圖片,反之不能更改這兩個屬性值

二.ListView:存儲項集合

Items ListView中的項
View 指定那種視圖顯示
LargeImageList 大圖標圖像的ImageList控件
SmallImageList 小圖標圖像的ImageList控件


三.ContextMenuStrip

Items 快捷菜單項的集合
DisplayStyle 每一項顯示的狀態(文字,圖像)

在控件上選擇ContextMenuStrip屬性綁定快捷菜單

四.動態綁定ListView中的數據

#region 動態綁定ListView中的數據

//定位到父項
ListViewItem itemc = new ListViewItem("C盤:",0);
//第一種:通過父項.SubItems.Add()添加單個子項
itemc.SubItems.Add("本地磁盤");
itemc.SubItems.Add("250GB");
itemc.SubItems.Add("1KB");

ListViewItem itemd = new ListViewItem("D盤:",1);
//方式二:通過父項.SubItems.AddRange()添加多個子項
itemd.SubItems.AddRange(new string[]{"本地磁盤","1TB","250GB"});


//最後一步:將父項以及父項的子項集合添加到ListView當中
this.lvwindows.Items.Add(itemc);
this.lvwindows.Items.Add(itemd);

//通過下標定位到父項然後添加子項列表數據
ListViewItem iteme = this.lvwindows.Items[2];
iteme.SubItems.AddRange(new string[] { "本地磁盤", "1TB", "250GB" });

#endregion

五.動態從數據庫獲取數據綁定
string constr = "Data Source=.;Initial Catalog=SchoolDB;User ID=sa;Password=.";
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string sql = @"select Grade.*,Student.* from Grade,Student where Grade.GradeId=Student.GradeId
and Student.StudentName like ‘%"+this.txtName.Text+"%‘ ";

SqlCommand com = new SqlCommand(sql,con);
SqlDataReader reader=com.ExecuteReader();
//判斷讀取出來的數據為不為空
if (reader.HasRows) {
while(reader.Read()){
ListViewItem item = new ListViewItem(reader["StudentNo"].ToString());
item.SubItems.AddRange(new string[] { reader["StudentName"].ToString(), reader["Sex"].ToString(), reader["GradeName"].ToString() });
item.Tag = (int)reader["StudentNo"];
this.lvStudentList.Items.Add(item);
}
}

}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
finally {
con.Close();
}

獲取選中項的Tag值:this.lvStudentList.SelectedItems[0].Tag.ToString()

使用ListView控件展示數據