TreeView添加图片

时间:2021-04-22 15:37:51

实现方式一:

通过代码方式实现如下所示:

   private string FilePath = Application.StartupPath + "\\Images\\";

            Image img = new Bitmap(FilePath + "one.ico");
Image img1 = new Bitmap(FilePath + "two.ico");
ImageList imgs = new ImageList();
imgs.Images.Add(img);
imgs.Images.Add(img1);
this.tvTest.ImageList = imgs; TreeNode node = new TreeNode();
node.Text = "Root";
this.tvTest.Nodes.Add(node);
node.ImageIndex = 0;
node.SelectedImageIndex = 0; TreeNode node1 = new TreeNode();
node1.Text = "root001";
TreeNode node2 = new TreeNode();
node2.Text = "root002";
node.Nodes.Add(node1);
node.Nodes.Add(node2);
this.tvTest.ExpandAll();
node1.ImageIndex =1;
node1.SelectedImageIndex = 1;
node2.ImageIndex = 1;
node2.SelectedImageIndex = 1;

实现方式二:

通过绑定ImageList控件实现,如下所示:

操作步骤:第一步,工具箱中拖动ImageList控件;第二步,ImageList控件Images属性添加图片集合;第三步,TreeView控件绑定ImageList属性;

第四步,代码如下所示:

            TreeNode node = new TreeNode();
node.Text = "Root";
this.tvTest.Nodes.Add(node);
node.ImageIndex = 0;
node.SelectedImageIndex = 0; TreeNode node1 = new TreeNode();
node1.Text = "root001";
TreeNode node2 = new TreeNode();
node2.Text = "root002";
node.Nodes.Add(node1);
node.Nodes.Add(node2);
this.tvTest.ExpandAll();
node1.ImageIndex =1;
node1.SelectedImageIndex = 1;
node2.ImageIndex = 1;
node2.SelectedImageIndex = 1;

运行效果如下:  

TreeView添加图片