gpt4 book ai didi

c# - DatagridView Column.DataPropertyName 到数组元素?

转载 作者:行者123 更新时间:2023-11-30 12:53:49 24 4
gpt4 key购买 nike

我正在使用 DataGridView 将其数据源绑定(bind)到列表,并为每一列指定属性。

一个例子是:

 DataGridViewTextBoxColumn colConcept = new DataGridViewTextBoxColumn();
DataGridViewCell cell4 = new DataGridViewTextBoxCell();
colConcept.CellTemplate = cell4;
colConcept.Name = "concept";
colConcept.HeaderText = "Concept";
colConcept.DataPropertyName = "Concept";
colConcept.Width = 200;
this.dataGridViewBills.Columns.Add(colConcept);

{...分配其他列...}

最后

 this.dataGridViewBills.DataSource=billslist; //billslist is List<Bill>

显然 Bill 类有一个名为 Concept 的属性,并且每一列都有一个属性。

好吧,现在我的问题是,Bill 应该拥有名为 Years 的数组/列表/任何动态大小的字符串容器。

假设每个 Bill 都具有相同的 Years.Count,但这仅在运行时已知。因此,我无法指定 Bill.FirstYear 等属性来获取 Bill.Years[0],Bill.SecondYear 来获取 Bills .Years[1]...等...并将其绑定(bind)到每一列。

我的想法是,现在我想要一个具有动态列数(在运行时已知)的网格,并且每列都填充 Bill.Years 列表中的一个字符串。我可以创建一个循环,根据 Bill.Years.Count 在运行时将列添加到网格,但可以将它们绑定(bind)到 Bill.Years 列表包含的每个字符串???

我不确定我是否足够清楚。

理想情况下,结果应该是这样的,列表中有 2 个账单,每个账单 3 年:

--------------------------------------GRID HEADER-------------------------------NAME      CONCEPT         YEAR1              YEAR2                YEAR3   --------------------------------------GRID VALUES-------------------------------Bill1     Bill1.Concept   Bill1.Years[0]     Bill1.Years[1]       Bill1.Years[2]Bill2     Bill2.Concept   Bill2.Years[0]     Bill2.Years[1]       Bill2.Years[2]

我总是可以忘记数据源,手动编写每个单元格,就像 MSFlexGrid 过去喜欢的那样,但如果可能的话,我想使用 DataGridView 的绑定(bind)功能。

有什么想法吗?非常感谢。

最佳答案

我最近遇到了同样的问题。我最终使用了 DataGridView 的虚拟模式,而不是绑定(bind)到数据源。它不具有与绑定(bind)完全相同的功能,但它仍然比手动填充每个单元格强大得多。

在虚拟模式下,DataGridView 会在需要显示单元格时触发事件,这实际上意味着您可以随心所欲地填充单元格:

    private void my_init_function() {
datagridview.VirtualMode = true;
datagridview.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(datagridview_CellValueNeeded);
}

private void datagridview_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
e.Value = get_my_data(e.RowIndex, e.ColumnIndex);
}

关于c# - DatagridView Column.DataPropertyName 到数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1505626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com