数据网格视图,每个单元格内都有自定义对象
本文关键字:自定义 对象 单元格 网格 数据网 视图 数据 | 更新日期: 2023-09-27 18:36:47
在C#中,我有DataGridView和我的自定义类"Thing",它们覆盖了toString()方法。我想要做的只是用事物类型的对象填充 DataGridView,以便事物对象可以在 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;
}
}
我正在尝试填充数据网格视图,例如:
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();
然后
在某个循环中,我尝试在 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
最后:
DataGridView1.DataSource = dt;
网格正确填充单元格和行,但它们为空。我希望他们从 Thing.text 字段中看到可见的文本。
我需要使用自定义对象来做到这一点,因为我希望将来很少有可用的东西。
那么如何做类,以便 DataGridView 可以以某种方式使用它来获取要在每个单元格上显示的文本值?
这奏效了:
for (int x = 0; x < Xnum; ++x) {
for (int y = 0; y < Ynum; ++y) {
dt.Rows[y][x] = new Thing("Cell " + x.ToString() + ", " + y.ToString(), -1);
}
}
确保您使用"事物"填充表格。