Reputation: 1
I'm new to C# and for a homework assignment I need to read a CSV file using openfiledialog then adding them to a list but I can't figure out how I can split the lines using a ','.
I have already tried to add .split after lines and I already tried adding value also but it doesn't allow it.
openFileDialog1.ShowDialog();
var fileName = openFileDialog.FileName;
using(StreamReader sr = new StreamReader(fileName))
{
List<Employee_Record> Employees = new List<Employee_Record>();
var lines = sr.ReadLine();
var value = lines.Split(',');
Employees.Add(new Employee_Record() { Name = lines, Address = lines, Age = lines, GrossMonthlyPay = lines, DepartmentID = lines, DeveloperType = lines, TaxType = lines });
dataGridView1.DataSource = Employees;
}
Upvotes: 0
Views: 79
Reputation: 2166
Assuming you have a CSV like this one:
2A,18,Stephen Hawk,math,96
I would simply use regEx with C# to parse it.
openFileDialog1.ShowDialog();
var fileName = openFileDialog.FileName;
using(StreamReader sr = new StreamReader(fileName))
{
List<Employee_Record> Employees = new List<Employee_Record>();
var lines = sr.ReadLine();
Regex re = new Regex(@"\W?");
MatchCollection mc = re.Matches(lines);
int mIdx=0;
foreach (Match m in mc){
Console.writeline(m.Value);
}
// Do your logic here as you wish
}
//Expected output 2A 18 Stephen Hawk math 96
Upvotes: 1
Reputation: 5381
You have to access the value array. Not the lines. And you need a loop to read line by line.
using(StreamReader sr = new StreamReader(fileName))
{
List<Employee_Record> Employees = new List<Employee_Record>();
while((line = sr.ReadLine()) != null)
{
var value = line.Split(',');
//// some positions can be empty. So handle that
Employees.Add(new Employee_Record()
{
Name = value[0] ,
Address = value[1] ,
Age = value[2] ,
GrossMonthlyPay = value[3] ,
DepartmentID = value[4] ,
DeveloperType = value[5] ,
TaxType = value[6]
});
}
dataGridView1.DataSource = Employees;
}
Upvotes: 2