2010-12-01 94 views
0

我有一个列表视图和一个“添加”按钮,当我点击添加我应该能够浏览计算机中的文件,选择文件,当点击确定或打开时,文件列表应该被添加到列表视图...如何做到这一点...是列表视图正确或任何其他替代...?将文件添加到C#中的列表视图

+1

什么样的应用,这是? Windows窗体? ASP.NET? WPF? – JeffFerguson 2010-12-01 02:58:45

回答

3

ListView应该适用于文件列表。请注意,如果您要将完整路径添加到列表中,则较长的文件路径很难看到(必须水平滚动,这很糟糕!)。您可以玩具与其他代表的想法一样:

File.Txt (C:\Users\Me\Documents) 
C:\Users\..\File.Txt 
etc 

至于使用代码而言这样做,你将需要使用OpenFileDialog控制,让用户选择文件。

var ofd = new OpenFileDialog(); 
//add extension filter etc 
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ; 
if(ofd.ShowDialog() == DialogResult.OK) 
{ 
    foreach (var f in openFileDialog1.FileNames) 
    { 
     //Transform the list to a better presentation if needed 
     //Below code just adds the full path to list 
     listView1.Items.Add (f); 

     //Or use below code to just add file names 
     //listView1.Items.Add (Path.GetFileName (f)); 
    } 
} 
+1

有关缩短路径的更多信息和一些不同的策略,请查看Jeff的[博客文章](http://www.codinghorror.com/blog/2006/08/shortening-long-file-paths.html)学科。其实质是您可以使用正则表达式或[`PathCompactPathEx` API](http://msdn.microsoft.com/zh-cn/library/bb773578.aspx)自动执行此操作。 – 2010-12-01 04:10:40

+0

@hemanth:thanx ...如何只显示选定的文件名? – 2010-12-01 04:45:21

2

如果你想做到这一点的设计师,你可以采取以下步骤将图像添加到ListView控件:

  1. 切换到设计师,单击该ImageList组件上组件托盘中,ImageList的右上角会出现一个智能标签。
  2. 单击智能标签,然后单击窗格上的“选择图像”。
  3. 在弹出的图像集合编辑器对话框中,从您想要的文件夹中选择图像。
  4. 单击确定完成将图像添加到ImageList。
  5. 单击窗体上的ListView,右上角会出现一个智能标签。
  6. 单击智能标签,您会发现那里有三个组合框,您可以根据需要从列表中选择一个ImageList。
  7. 单击智能标签上的“添加项目”选项,将出现一个ListViewItem集合编辑器,您可以将项目添加到ListView,这里设置ImageIndex或ImageKey属性很重要,否则图像将不会出现。
  8. 单击确定完成项目编辑,现在您会发现图像显示在ListView上。

如果你想给图像添加到通过代码ListView控件,你可以做这样的事情

给下面的代码在addButton_click

 var fdlg = new OpenFileDialog(); 
     fdlg.Multiselect = true; 
     fdlg.Title = "Select a file to add... "; 
     fdlg.InitialDirectory = "C:\\"; 
     fdlg.Filter = "All files|*.*"; 
     fdlg.RestoreDirectory = true; 
     if (fdlg.ShowDialog() == DialogResult.OK) 
     { 
      foreach (var files in fdlg.FileNames) 
      { 
       try 
       { 
        this.imageList1.Images.Add(Image.FromFile(files)); 
       } 

       catch (Exception ex) 
       { 
        MessageBox.Show(ex.Message); 
       } 
      } 
      this.listView1.View = View.LargeIcon; 
      this.imageList1.ImageSize = new Size(32, 32); 
      this.listView1.LargeImageList = this.imageList1; 
      //or 
      //this.listView1.View = View.SmallIcon; 
      //this.listView1.SmallImageList = this.imageList1; 
      for (int j = 0; j < this.imageList1.Images.Count; j++) 
      { 
       ListViewItem item = new ListViewItem(); 
       item.ImageIndex = j; 
       this.listView1.Items.Add(item); 
      } 
     }