【问题标题】:Hide/modify string in listView在 listView 中隐藏/修改字符串
【发布时间】:2017-05-29 09:21:22
【问题描述】:

我正在制作一个程序,用户可以在其中修改远程文件。我将选定的文件(取决于一些预定义的条件)放在 listView 中,但我只显示文件名,而不是完整的文件路径。

然而,我遇到的问题是,当用户双击一个项目时,它应该打开另一个窗口来修改该项目。

private void listView1_DoubleClick(object sender, EventArgs e)
{
    account = File.ReadAllLines("\\\\myremoteserver\\ftp\\"+listView1.SelectedItems[0].Text+".txt");   
    Form3 passForm = new Form3();
    passForm.ShowDialog();
}

private void Form2_Load(object sender, EventArgs e)
{
    string[] files = Directory.GetFiles("\\\\myremotserver\\ftp\\","*.txt", System.IO.SearchOption.AllDirectories);
    foreach (string s in files)
    {
        listView1.Items.Add(Path.GetFileNameWithoutExtension(s));
    }
}

问题是,这些文件都在不同的子文件夹中,所以如果我保持原样,它将不会显示文件的正确内容。比如文件叫test1.txt,放在myremoteserver\ftp\testfolder\test1.txt,但是用我的程序,会尝试在myremoteserver\ftp\test1.txt找文件。

我要问的是,如果有可能以这样的方式修改 listView,总是保存完整的文件路径,但只显示文件名?我不希望用户看到文件的完整文件路径,只看到文件名。

【问题讨论】:

  • 如果 listview 项目有 .tag 属性,您可以在其中保存完整路径
  • 或者最好在 listView1.Items.Add 方法中添加一个键入的项目,并使用 DisplayMember (msdn.microsoft.com/en-us/library/…) 仅在列表视图中显示名称。
  • 我很可能会使用 .tag 属性,谢谢,它有效,我只需要将 foreach 循环换成 for 循环。 @Digvijay 为什么会更好?
  • 这个(使用 .Tag )只要它只是你需要使用的字符串就可以工作 - 但是一旦你意识到你需要使用 INotifyPropertyChange 更新列表,标签方法就会失败!
  • 该列表很可能永远不会更新,因为我只使用它来根据用户定义的参数在程序启动时显示文件。

标签: c# winforms listview


【解决方案1】:

使用 ListViewItem 的 Tag 属性

所以要创建项目...

foreach (string s in files)
{
    ListViewItem lvi = new ListViewItem(Path.GetFileNameWithoutExtension(s));
    lvi.Tag = s;
    listView1.Items.Add(lvi);
}

然后在事件处理程序中...

account = File.ReadAllLines("\\\\myremoteserver\\ftp\\"+listView1.SelectedItems[0].Tag +".txt);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2012-01-23
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2013-01-17
    • 1970-01-01
    相关资源
    最近更新 更多