【发布时间】:2022-01-22 02:07:20
【问题描述】:
我是编程新手,在这里需要帮助...我想创建一个带有组合框项的绑定。 但是 DataBinding 没有添加新的 DataBind,它会覆盖旧的,因为循环。所以我想如果你在组合框中选择一个“Profilname”,就会显示“路径”。
但到目前为止,由于覆盖,只会显示最后加载的 .txt 文件。
现在我的问题是:如何避免在 (foreach) 循环中覆盖 DataBind?
有关信息:有一个文件夹包含许多 .txt 文件,这些文件都称为:“profile.txt”。程序用一个循环搜索所有文件,然后用另一个循环在文件中搜索一行,其中包含单词“profile_name”。然后名称必须显示在组合框中,路径必须绑定到组合框中的“项目”/“文本”。
如果我的代码令人困惑或写得不是很强大,我希望这是可以理解和抱歉的,我正在学习......
foreach (string profiletxt in Directory.EnumerateFiles(profiledirectory, "profile.txt", SearchOption.AllDirectories))
{
foreach (string line in System.IO.File.ReadAllLines(profiletxt))
{
if (line.Contains("profile_name"))
{
string remLine = line.Remove(0, 15);
string dLine = remLine.Replace("\"", "");
// dataBinding
var listProfiles = new List<Profile>() {
new Profile() {Path = profiletxt, Name = dLine,},
};
materialComboBox1.DataSource = listProfiles;
materialComboBox1.DisplayMember = "Name";
materialComboBox1.ValueMember = "Path";
}
}
if (materialComboBox1.SelectedIndex == -1)
{
MessageBox.Show("Error, couldn't find Profiles");
}
}
public class Profile
{
public string Path { get; set; }
public string Name { get; set; }
}
【问题讨论】:
-
您可能希望在循环内将项目添加到
listProfiles,然后在处理完所有文件后在循环外分配绑定。
标签: c# data-binding