我正在访问.CSV文件并转换要在DataGrid中显示的值,我的问题是我只有一个已定义的实例,它曾经在循环之外,我没有设置它的属性。
如何在循环中创建多个实例并在我使用时设置属性值?
CSV格式为: “标题” 'string,string,int,string'(最多300个条目)
以下是主要代码,点击菜单 - >打开:
// Function to open a .CSV file and assign the values within to a List.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Stock> stocks = new List<Stock>();
// Set strings to retrieve current directory and store stocklist.csv as "filename"
string filename = @"C:\StockFile\stocklist.csv";
// Read all lines in file and set indexer to 0.
string[] linesInFile = File.ReadAllLines(filename);
string[] StockDetails = new string[0];
for (int i = 1; i < linesInFile.Length; i++)
{
// Load lines in file and increment by 1.
string currentLine1 = linesInFile[i];
// Split the current line by separator ,
StockDetails = currentLine1.Split(',');
Stock item = new Stock();
stocks.Add(item);
}
var list = new BindingList<Stock>(stocks);
stockGridView.DataSource = list;
}
这是我的Stock类:
class Stock
{
public string Code { get; internal set; }
public string Desc { get; internal set; }
public int CurCnt { get; internal set; }
public string Order { get; internal set; }
public Stock(string code, string desc, int curcnt, string order)
{
Code = code;
Desc = desc;
CurCnt = curcnt;
Order = order;
}
}
答案 0 :(得分:0)
如果我理解你要做什么,你需要初始化Stock项的实例,并且每次在循环中new关键字将创建它的新实例并将创建的实例添加到列表
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Stock> stocks = new List<Stock>();
// Set strings to retrieve current directory and store stocklist.csv as "filename"
string filename = @"C:\StockFile\stocklist.csv";
// Read all lines in file and set indexer to 0.
string[] linesInFile = File.ReadAllLines(filename);
string[] StockDetails = new string[0];
for (int i = 1; i < linesInFile.Length; i++)
{
// Load lines in file and increment by 1.
string currentLine1 = linesInFile[i];
// Split the current line by separator ,
StockDetails = currentLine1.Split(',');
Stock item = new Stock(StockDetails[0],StockDetails[1],StockDetails[2],StockDetails[3]);
stocks.Add(item);
}
var list = new BindingList<Stock>(stocks);
stockGridView.DataSource = list;
}