[ Adding a Collection to a DataGridView ]

To add a collection to a datagridview, the first thing you need to understand that
a) You need to have DataMembers (or descriptors for the data)
b) Certain objects or datatypes are not thread-safe
c) Certain datatypes do not notify of changes and thus cannot update the view
In a seperate thread I have a static Queue which keeps a list of all the lines I find as a match in an outputstream.
public static Queue matches = new Queue();

Next I create a class as a data structure to allow the DataGridView to understand what members to access or data.
class ResultsMatch


public string Line { get; set; }

public int Resultnumber { get; set; }
public ResultsMatch(int resultnumber, string line)
Resultnumber = resultnumber;
Line = line;

Next we will create a bindingsource to be used for our DataGridView

bindingsrc = new BindingSource();
int i = 0;
foreach (string match in frmMain.matches)
bindingsrc.Add(new ResultsMatch(i, match));

And finally our DataGridViewTextBoxColumns

DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Resultnumber";
column.Name = "Match Number";
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Line";
column.Name = "Line Matched";
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dgvResults.AutoSize = true;
dgvResults.AutoGenerateColumns = false;
dgvResults.DataSource = bindingsrc;

So that should be it….
Don't be shellfish...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

Leave a Reply