我有一个列表,其中填充了来自 CSV 文件的数据,但是当我将该列表设置为 datagridview 数据源属性时,没有显示任何数据。你能指出我可能犯错的地方吗?
这是我的代码
var csvlines = File.ReadAllLines(filename); // IEnumerable<string>
var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); // IEnumerable<string[]>
var users = csvLinesData.Select(data => new User
{
CSRName = data[6],
CallStart = data[0],
CallDuration = data[1],
RingDuration = data[2],
Direction = data[3],
IsInternal = data[4],
Continuation = data[5],
ParkTime = data[7]
}).ToList();
dataGridView1.DataSource = users;
编辑
现在我这样做了,数据正在显示。
var csvlines = File.ReadAllLines(filename); // IEnumerable<string>
var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); // IEnumerable<string[]>
var users = csvLinesData.Select(data => new User
{
CSRName = data[12],
CallStart = data[0],
CallDuration = data[1],
RingDuration = data[2],
Direction = data[4],
IsInternal = data[8],
Continuation = data[10],
ParkTime = data[18]
}).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("CSRName",typeof(string));
dt.Columns.Add("CallStart", typeof(string));
dt.Columns.Add("CallDuration", typeof(string));
dt.Columns.Add("RingDuration", typeof(string));
dt.Columns.Add("Direction", typeof(string));
dt.Columns.Add("IsInternal", typeof(string));
dt.Columns.Add("Continuation", typeof(string));
dt.Columns.Add("ParkTime", typeof(string));
DataRow dr = null;
foreach (var user in users)
{
dr = dt.NewRow();
dr["CSRName"] = user.CSRName;
dr["CallStart"] = user.CallStart;
dr["CallDuration"] = user.CallDuration;
dr["RingDuration"] = user.RingDuration;
dr["Direction"] = user.Direction;
dr["IsInternal"] = user.IsInternal;
dr["Continuation"] = user.Continuation;
dr["ParkTime"] = user.ParkTime;
dt.Rows.Add(dr);
}
//dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
将网格视图绑定到 BindingList,而不是 List。
var bindlist = new BindingList<User>(users);
然后创建一个绑定源并将其绑定到 gridview。
var source = new BindingSource(bindlist, null);
dataGridView1.DataSource = source;