Reputation: 2053
C#, .Net 4, VS2010
I have an object that contains multiple arrays of doubles (recently made them into Lists). It looks something like:
public class Channel
{
public List<DateTime> Date = new List<DateTime>(); //DateTime
public List<double> Val1 = new List<double>(); //
public List<double> Val2 = new List<double>(); //
public List<double> Val3 = new List<double>(); //
public List<double> Val4 = new List<double>(); //
}
So now I'm trying to populate a DataGridView
with a DataSource
, but I only care about Date
, Val1
, and Val2
. How can I achieve this?
Currently I'm looping through the arrays and adding them row by row to the DataGridView
. But this is really slow as I have a huge file of data to work with. Isn't there an easy way to just bind my arrays and populate the grid? I can't seem to figure it out.
Thanks
Code I've tried:
Channel ch = new Channel();
List<object> datasource = new List<object>();
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
datasource.Add(ch.spotsList[0].Date);
datasource.Add(ch.spotsList[0].Val1);
datasource.Add(ch.spotsList[0].Val2);
dataGridView1.DataSource = datasource;
Code I'm using that works but is really slow:
for (int i = 0; i < ch.spotsList[0].Date.Count; i++)
{
dataGridView1.Rows.Add(ch.spotsList[0].Date[i].ToString("yyyy-MM-dd HH:mm:ss"), ch.spotsList[0].Val1[i].ToString("#.##"), ch.spotsList[0].Val2[i].ToString("#.##"));
}
Upvotes: 0
Views: 1029
Reputation: 25
You can implement the ITypedList interface. This way you can control the generated columns.
Upvotes: 0
Reputation: 5245
DataGridViews
aren't really designed for data models structured by column (such as yours). Rather, they are meant to be used with models that represent a row. It seems like your edit indicates that you are starting to think along those lines. In particular, hopefully your new data model is something like
public class Channel
{
private _listings = new List<SpotsList>();
public IList<SpotsList> SpotsList { get { return _listings; } }
}
public class SpotsList
{
public DateTime Date { get; set; }
public double Val1 { get; set; }
public double Val2 { get; set; }
public double Val3 { get; set; }
public double Val4 { get; set; }
}
In which case, you should be able to load this into your DataGridView
via the call
Channel ch = new Channel();
// Add data to the channel
dataGridView1.DataSource = ch.SpotsList;
Edit
To try and more clearly communicate what I am thinking, the code below should help you map your approach to my approach.
public class DataPoint
{
public DateTime Date { get; set; }
public double Val1 { get; set; }
public double Val2 { get; set; }
}
// ... your other code ...
var dataSource = new List<DataPoint>();
for (int i = 0; i < ch.spotsList[0].Date.Count; i++)
{
dataSource.Add(new DataPoint()
{
Date = ch.spotsList[0].Date[i],
Val1 = ch.spotsList[0].Val1[i],
Val2 = ch.spotsList[0].Val2[i]
});
}
dataGridView1.DataSource = dataSource;
Upvotes: 2