У меня есть программа на C# для чтения данных из ".csv" и отображения в виде таблицы данных. Основной код для чтения и отображения показан ниже. Он выполняется при нажатии кнопки.
StreamReader sr = null;
List<LogList> loglist = new List<LogList>();
BindingList<LogList> bindLogList;
BindingSource bLogsource;
dLogView.DataSource = null;
dLogView.Rows.Clear();
dLogView.Columns.Clear();
{
// code to add data to custom list
// the list has 12 fields.
sr = new StreamReader("C:\\VSWR_T&M\\Log\\20200423.csv");
int count = 0;
// skip the first line read containing header, save from second line onwards.
StringBuilder readLine = new StringBuilder(sr.ReadLine());
if (readLine.ToString() != null && readLine.ToString() != "")
{
readLine = new StringBuilder(sr.ReadLine());
while (readLine.ToString() != null && readLine.ToString() != "")
{
string[] subdata = readLine.ToString().Split(',');
count = subdata.Length;
LogList ll = new LogList(subdata[0], subdata[1], subdata[2], subdata[3], subdata[4], subdata[5], subdata[6], subdata[7], subdata[8], subdata[9], subdata[10], subdata[11]);
loglist.Add(ll);
readLine = new StringBuilder(sr.ReadLine());
}
}
}
bindLogList = new BindingList<LogList>(loglist);
bLogsource = new BindingSource(bindLogList, null);
dLogView.AutoGenerateColumns = true;
dLogView.DataSource = bLogsource;
dLogView.Columns[0].Width = 100;
dLogView.Columns[1].Width = 120;
dLogView.Columns[2].Width = 50;
dLogView.Columns[3].Width = 50;
dLogView.Columns[4].Width = 50;
dLogView.Columns[5].Width = 50;
dLogView.Columns[6].Width = 50;
dLogView.Columns[7].Width = 50;
dLogView.Columns[8].Width = 50;
dLogView.Columns[9].Width = 50;
dLogView.Columns[10].Width = 50;
dLogView.Columns[11].Width = 50;
Класс LogList выглядит следующим образом:
class LogList
{
string project { get; set; }
string date_time { get; set; }
string Qty { get; set; }
string Pass { get; set; }
string Fail { get; set; }
string Result { get; set; }
string ANT2_1 { get; set; }
string ANT2_2 { get; set; }
string ANT2_3 { get; set; }
string ANT3_1 { get; set; }
string ANT3_2 { get; set; }
string ANT3_3 { get; set; }
public LogList(string project, string date_time, string Qty, string Pass, string Fail, string Result, string ANT2_1, string ANT2_2,
string ANT2_3, string ANT3_1, string ANT3_2, string ANT3_3)
{
this.project = project;
this.date_time = date_time;
this.Qty = Qty;
this.Pass = Pass;
this.Fail = Fail;
this.Result = Result;
this.ANT2_1 = ANT2_1;
this.ANT2_2 = ANT2_2;
this.ANT2_3 = ANT2_3;
this.ANT3_1 = ANT3_1;
this.ANT3_2 = ANT3_2;
this.ANT3_3 = ANT3_3;
}
}
Когда я запускаю этот код, я получаю сообщение об исключении, которое говорит
"Index was out of range. Must be non-negative and less than the size of the collection.
parameter name: Index"
Исключение генерируется из строки
dLogView.Columns[1].Width = 120;
Кажется, столбцы не добавлены. Я пропускаю какое-то свойство столбца здесь? Я хотел бы знать, почему столбцы не добавляются?