Pla*_*ato 1 c# combobox winforms
我在ac#windows form app项目中有一个组合框,我使用以下代码使组合框显示到文件夹的内容
string path = Path.GetFullPath("a").Replace(@"\bin\Debug\a", "") + @"\Files";
BotOptions.DataSource = Directory.GetFiles(path);
Run Code Online (Sandbox Code Playgroud)
它确实有效,但组合框包含文件夹中文件的完整路径,我想问你的是有没有办法让它成为组合框只会显示文件名但是组合框的实际值还会保持完整的路径吗?
您可以将组合框的DataSource设置为DirectoryInfo类返回的FileInfo列表,然后将ValueMember设置为FullName属性,将DisplayMember设置为Name属性
string path = Path.GetFullPath("a").Replace(@"\bin\Debug\a", "") + @"\Files";
DirectoryInfo de = new DirectoryInfo(path);
BotOptions.DataSource = de.EnumerateFiles().ToList();
BotOptions.ValueMember = "FullName";
BotOptions.DisplayMember = "Name";
Run Code Online (Sandbox Code Playgroud)
现在要获取文件的全名,请使用属性SelectedValue
string fullPath = BotOptions.SelectedValue?.ToString();
Run Code Online (Sandbox Code Playgroud)
最后,无论您想对该文件执行什么操作,请记住ComboBox中的每个项目都是FileInfo实例,因此您可以读取SelectedItem属性以发现有关所选文件的信息,如Attributes,CreationDate,Length等...
if(BotOptions.SelectedItem != null)
{
FileInfo fi = BotOptions.SelectedItem as FileInfo;
Console.WriteLine("File length: " + fi.Length);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |