【发布时间】:2021-04-12 19:40:21
【问题描述】:
我想做一个这样的组合框:
但是这些框不应该是硬编码的,它们应该来自这样的文本文件:
在文本文件中添加数据应导致添加组合框。每个组合框也应该有相同的选项列表,它们是 1,2,3,4
我做了以下类来读写文本文件,但是我在互联网上找不到任何资源来将这些文本文件转换为组合框。
public static string ReadFromTextFile(string path)
{
if (File.Exists(path))
{
string data;
using (StreamReader r = new StreamReader(path))
{
data = r.ReadToEnd();
}
if (data != "")
{
data = "[" + data + "]";
}
return data;
}
return null;
}
public static void WriteToTextFile(string path, string data, bool append = true, int count = 1)
{
if (!File.Exists(path))
{
var file = File.Create(path);
file.Close();
}
using (StreamWriter writer = new StreamWriter(path, append: append))
{
if (!append)
{
//remove opening bracket "[" from data passed
data = data.Trim().Substring(1, data.Trim().Length - 1);
//remove last bracket "]" from data passed
data = data.Trim().Substring(0, data.Trim().Length - 1);
}
if (count != 0)
{
data = data + ",";
}
writer.WriteLine(data);
}
}
public static DataTable ConvertToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
if (data != null)
{
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
}
return table;
}
【问题讨论】:
-
快速浏览一下您的代码与您的问题不符。您的文本文件显示
Food,<new-line>Water,,而您的代码正在解析方括号并使用 DataTables 执行某些操作。你需要重写你的问题 -
是的,如果文本文件包含所有必需的信息(名称、选择选项等),则可以
标签: c# .net visual-studio winforms combobox