修剪列表框vb.net中的字符 [英] Trim characters from listbox vb.net

查看:74
本文介绍了修剪列表框vb.net中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个填充文件名的列表框.我想从列表框中每个文件名的开头删除路径.我不知道该如何解决

列表框内容示例

y:\ filename1.txt
y:\ filename2.txt
y:\ filename3.txt


每个文件名的目录将始终相同

谢谢
J

Hi,
I have a list box populated with file names. I want to remove the path from the start of each filename in the list box. I have no idea how to get around this

Example of list box contents

y:\filename1.txt
y:\filename2.txt
y:\filename3.txt


The directory will always be the same for each filename

Thanks
J

推荐答案

您可以使用利用列表框的Format事件对items集合中的值执行几乎所有操作.只需使用System.IO.Path.GetFileName将显示的值修整为仅文件名即可.


例如
You can use utilise the Format event of the listbox to do pretty much anything to the values in the items collection. Just use System.IO.Path.GetFileName to trim the displayed value back to the filename only.


e.g.
public Form1() {
  InitializeComponent();
  this.listBox1.FormattingEnabled = true;
  listBox1.Format += new ListControlConvertEventHandler(listBox1_Format);
  listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
  listBox1.DataSource = Directory.GetFiles(Environment.CurrentDirectory);
}

private void listBox1_Format(object sender, ListControlConvertEventArgs e) {
  // display filename only
  e.Value = System.IO.Path.GetFileName((String)e.Value);
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
  // Still have the full path
  label1.Text = (String)listBox1.SelectedItem;
}




在VB中也一样!




and in VB too!

Public Sub New()
    InitializeComponent()
    Me.listBox1.FormattingEnabled = True
    listBox1.Format += New ListControlConvertEventHandler(AddressOf listBox1_Format)
    listBox1.SelectedIndexChanged += New EventHandler(AddressOf listBox1_SelectedIndexChanged)
    listBox1.DataSource = Directory.GetFiles(Environment.CurrentDirectory)
End Sub

Private Sub listBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
    label1.Text = DirectCast(listBox1.SelectedItem, String)
End Sub

Private Sub listBox1_Format(sender As Object, e As ListControlConvertEventArgs)
    e.Value = Path.GetFileName(DirectCast(e.Value, String))
End Sub





艾伦.





Alan.


您可以使用 ^ ].

例如,如果要在最后一个\之后获取文本,则代码可能类似于:

You can use SubString[^] for this.

For example if you want to get the text after the last \ then the code could look something like:

string path = "y:\\filename1.txt";
string file = path.Substring(path.LastIndexOf('\\') + 1);



抱歉,您将此标签为VB:



Sorry, you tagged this as VB:

Dim path As String = "y:\\filename1.txt"
Dim file As String = path.Substring(path.LastIndexOf('\\') + 1)


这篇关于修剪列表框vb.net中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆