ListView控件的使用
近日在用ListView中的一些注意点,和公用代码,整理如下
1.ListView.Items.Clear而不是ListView.Clear
一般如果ListView是动态填充的,我们在填充之前都会先进行清理。但需要注意一下,我们是清理Items,如果去直接Clear整个ListView,就连原先定义好的列都没有了
2.给ListView绑定数据
ListView并不能直接进行绑定,而是要通过代码。究其原因,因为它在绑定的时候,还需要设置图片等信息。而ListView一般都与TreeView配合使用,它的绑定行为是通过TreeView的点击来引发的
/// <summary>
/// 当点击了左边的Treeview的时候触发事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void treeView1_NodeMouseClick(object sender,
TreeNodeMouseClickEventArgs e)
{
TreeNode node = e.Node;
List<DTOStudent> result = new List<DTOStudent>();
if (node.Nodes.Count == 0)//如果不是根节点
{
//按照专业读取学员信息
result = dal.GetStudentBySpec(node.Text);
}
else
{
//读取全部学员信息
result = dal.GetAllStudents();
}
BindListView(result);
}
private void BindListView(List<DTOStudent> result)
{
//将ListView先进行清理
//一定要注意,是Items.Clear,而不是ListView1.Clear
listView1.Items.Clear();
//两个ImageList也清理一下(因为是动态添加图片)
imageList1.Images.Clear();
imageList2.Images.Clear();
int i = 0;
foreach (DTOStudent student in result)
{
ListViewItem item = new ListViewItem(student.UID);
//动态得到每个学员所对应的图片
Image image = Utility.ImageProcessor.ConvertToImage(student.Photo);
//加入到两个ImageList里面去
//这两个ImageList与ListView的LargeIcon和SmallIcon对应
imageList1.Images.Add(image);
imageList2.Images.Add(image);
item.ImageIndex = i;
i++;
listView1.Items.Add(item);
item.SubItems.Add(student.Age.ToString());
item.SubItems.Add(student.FirstName);
item.SubItems.Add(student.LastName);
}
}
3.切换ListView的显示视图
private void 大图标ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.LargeIcon;
}
private void 小图标ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.SmallIcon;
}
private void 清单ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.List;
}
private void 详细详细ToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.View = View.Details;
}
4.一些公用代码(图片和字节转换)
using System.Drawing;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace Utility
{
public class ImageProcessor
{
/// <summary>
/// 把图片转换为字节(主要是考虑存储到数据库)
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static byte[] ConvertToBytes(string fileName) {
Image image = Image.FromFile(fileName);
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, image);
byte[] result = new byte[ms.Length];
ms.Position = 0;
ms.Read(result, 0, result.Length);
ms.Close();
return result;
}
/// <summary>
/// 从字节再生成一个图片(主要是从数据库读取)
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static Image ConvertToImage(byte[] buffer) {
MemoryStream ms = new MemoryStream(buffer);
BinaryFormatter bf = new BinaryFormatter();
Image result = (Image)bf.Deserialize(ms);
ms.Close();
return result;
}
}
}
大致截图如下