Monday, 10 October 2016

c# - DataGridView with custom object inside each cell

In C# I have DataGridView and my custom class "Thing" that have override on toString() method.
All I want to do is to populate DataGridView with objects of a Thing type, and so the Thing objects can display them self on the DataGridView.



public class Thing
{
public string text {get;set;}
public int id {get;set;}


public Thing(string text, id)
{
this.text = text;
this.id = id;
}

public override string ToString()
{
return text;
}

}


and I am trying to populate DataGridView for example:



DataTable dt = new DataTable();
int Xnum = 100;
int Ynum = 100;

for (int i = 0; i < Xnum; i++)

dt.Columns.Add(i.ToString(), typeof(Thing));

for (int i = 0; i < Ynum; i++)
dt.Rows.Add();


and then



in some loop I try to fill values of the created cells in dt:




//loop
(dt.Rows[x][y] as Thing).text = "some text from loop";
(dt.Rows[x][y] as Thing).id = "some id from loop";
//end loop


And at the end:



DataGridView1.DataSource = dt;



Grid correctly populate with cells and rows but they are empty. I want them to have visible text on it from Thing.text fields.



I need to do it with custom object cause I want few things there to be available in future.



So how to do class so DataGridView can use it somehow to get text value to display on each cell?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...