更新时间:2023-10-14 14:58:04
你好,
您不必将值保存到另一个文件。您可以将它们加载到内存中的集合(如List),然后绑定到DataGridView。这里有一些示例:
Hi,
You don't have to save values to another file. You can load them to collection (like List) in memory and then bind to DataGridView. Here you have some sample:
// Always check if file Exists
if (!File.Exists(txtSelFile.Text))
{
throw new FileNotFoundException();
}
string[] lines = File.ReadAllLines(txtSelFile.Text);
string BC = string.Empty;
string PrevBcode = string.Empty;
// Create list of string type and store barcodes loaded from file.
List<string> barcodes = new List<string>();
foreach(string s in lines)
{
string[] fname1 = s.Split('|');
if (fname1[0] == "AAA")
{
BC = fname1[2];
if (BC != PrevBcode)
{
PrevBcode = fname1[2];
barcodes.Add(BC);
}
}
}
// Now we have loaded data in our LIST so we can bind it DataGridView
// You can't bing List<string> to datagridview because List<string> has no property to Bind.
// So we can create anonynous type:
dataGridView1.DataSource = barcodes.Select(x => new { Value = x }).ToList();</string></string></string></string>
另一种解决方案是创建用于存储类似此字符串值的类(将其保存在项目的StringValueClass.cs文件中:
Another solution is to create class for storing string values like this one (save it in StringValueClass.cs file in your project:
public class StringValueClass
{
public string StringValue { get; set; }
public StringValueClass(string value)
{
StringValue = value;
}
}
并修改您的数据加载代码:
And modify your data loading code:
List<StringValueClass> barcodes = new List<StringValueClass>();
foreach (string s in lines)
{
string[] fname1 = s.Split('|');
if (fname1[0] == "AAA")
{
BC = fname1[2];
if (BC != PrevBcode)
{
PrevBcode = fname1[2];
barcodes.Add(new StringValueClass(BC));
}
}
}
dataGridView1.DataSource = barcodes;
如果你在DataGridView组件中添加了列,确保该列已将DataPropertyName设置为:StringValue
学习集合的良好开端是MSDN:
http://msdn.microsoft.com/en- us / library / system.collections.generic%28v = vs.110%29.aspx [ ^ ]
而不是使用文本框控件获取文件路径,您可以考虑使用OpenFileDialog:
http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog%28v=vs.110%29.aspx [ ^ ]
我希望你觉得这很有用。
If you added column in DataGridView component, make sure that column has set DataPropertyName set to: StringValue
Good start for learning about collections is MSDN:
http://msdn.microsoft.com/en-us/library/system.collections.generic%28v=vs.110%29.aspx[^]
Instead of using textbox control to get file path you may consider using OpenFileDialog:
http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog%28v=vs.110%29.aspx[^]
I hope you find this useful.