【发布时间】:2013-01-15 21:18:04
【问题描述】:
理论上我该怎么做。
简短:使用自定义集合像数据表一样存储数据,具有可变数量的字段和列...只要行是一致的。
啰嗦:
2 或 3 个类:字段、行,可选:表
通常我会做类似List<Person> myList = new List<Person>;
然后该列表可以绑定到 datagridview 并且列将基于 Person 类的属性。
查看代码:
List<row> table = new List<row>;
List<field> row0 = new List<field>;
row0.Add(new field(col1,"value1"));
row0.Add(new field(col2,"value2"));
row0.add(new field(col3,"value3"));
table.Add(row0);
dataGridView1.DataSource = table;
理论输出:
| |col 1 | col 2| col 3|
___________________________
|row0|value1|value2|value3|
public class cField
{
public string Name { get; set; }
public string Content { get; set; }
public cField()
{
}
public cField(string name, string content)
{
Name = name;
Content = content;
}
}
public class cRow:BindingList<cField>
{
public cRow()
{
}
}
public class tables:BindingList<cRow>
{
public tables()
{
fillTestData();
}
private void fillTestData()
{
for (Int32 i = 0; i < 10; i++)
{
cRow tRow = new cRow();
for (Int32 x=0; x < 3; x++)
{
cField f1 = new cField("ColumnName" + x.ToString(), "content" + x.ToString());
tRow.Add(f1);
}
base.Items.Add(tRow);
}
}
}
//example class which shows the output of what I'd like.
public class eField
{
public string ColumnName0 { get; set; }
public string ColumnName1 { get; set; }
public string ColumnName2 { get; set; }
public eField(string colName0, string colName1, string colName2)
{
ColumnName0 = colName0;
ColumnName1 = colName1;
ColumnName2 = colName2;
}
}
public class eTable : BindingList<eField>
{
public eTable()
{
base.Add (new eField ("content","content", "content"));
base.Add(new eField("content", "content", "content"));
base.Add(new eField("content", "content", "content"));
}
}
现在是表单的代码。
public partial class Form1 : Form
{
tables t;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new tables ();
dataGridView1.DataSource = t;
dataGridView2.DataSource = t[0];
eTable table3 = new eTable ();
dataGridView3.DataSource = table3;
}
}
如果您将该代码放入项目中...您将看到第一个绑定...将一些内置内容从绑定列表中拉到 grid1 中。当我希望它们水平时,Grid2 会垂直列出我的字段。
网格 3 准确地显示了我希望我的输出如何......但是我无法使用要模仿数据表的集合结构来实现它......(在代码中提供)
免责声明: 我缺少研究这个问题所需的关键字。我没有找到太多。我发现的最接近的东西与 linq 和 pivots 有关。但他们的输出似乎都不像我描述的那样。
我在所有地方都使用自定义集合,所以我希望我的代码非常相似,而不是使用数据表。这是我第一次需要我的收藏以这种方式表现。
【问题讨论】:
-
我错过了一个实际问题,一个需要解决的问题。
-
即使您尝试详细解释,也不清楚您想要实现(或避免)什么。您知道可以将
List<Sometype>绑定到数据绑定控件,那么您不知道什么? -
问题是“我如何将一些自定义类构建在一起,使其像数据表对象一样执行”。答案可能是理论上的。我给出的代码示例不会像数据表那样显示在网格上,一旦行中添加了字段对象,就需要确定 n 列。
-
我遇到的问题是“列的可变数量”如果我有 List
其中 Person 有 3 个属性...我知道这 3 个属性将成为列。但是当需要由 List 定义列时,List 可能具有无限值。 -
见..哈哈。由于某种原因,我无法很好地描述这个问题,或者在网上搜索答案,因为我无法用语言表达它。我不知道这是否有帮助......但问题是嵌套列表需要在数据表和数据透视数据之间的某个地方起作用。或者,如果您想自己“自己,如果我要重新创建 MS 的 dataTable 对象...我如何将集合构造在一起以显示在网格上...网格可以有“x”个字段在运行时决定”
标签: c# data-binding collections