我正在尝试将结构表绑定到 DataGridView。加载和查看表格工作正常,但我无法编辑值并将其存储回表格中。这就是我正在做的事情。
我有一个“原始”数据类型,Real 定义为
public struct MyReal:IMyPrimative
{
public Double m_Real;
//...
public MyReal(String val)
{
m_Real = default(Double);
Init(val);
}
//...
}
它在结构中使用:
public struct MyReal_Record : IMyRecord
{
public MyReal Freq { get; set;}
MyReal_Record(String[] vals)
{
Init(vals);
}
}
并且该结构用于使用通用绑定列表定义表
public class MyTable<S> : BindingList<S> where S: struct, IMyRecord
{
public Type typeofS;
public MyTable()
{
typeofS = typeof(S);
// ...
}
此表用作网格的绑定源,动态。
private void miLoadFile_Click(object sender, EventArgs e)
{
MyModel.Table<Real_Record> RTable = new MyModel.Table<Real_Record>();
//... Table initialized here
//set up grid with virtual mode
dataGridView1.DataSource = RTable;
}
所有这些工作正常,我可以创建 RTable,初始化它并在网格中显示它。网格允许编辑,并为 CellParsing 和 CellFormatting 设置了事件,如下所示:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.DesiredType != typeof(String))
return;
e.Value = e.Value.ToString();
}
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
if (e.DesiredType != typeof(MyReal))
return;
e.Value = new MyReal(e.Value.ToString());
e.ParsingApplied = true;
this.dataGridView1.UpdateCellValue(e.ColumnIndex, e.RowIndex);
}
当我编辑单元格中的值时,我可以更改文本。离开单元格时,CellParsing 触发并调用事件处理程序。进入 CellParsing 处理程序的一切似乎都是正确的。e.DesiredType 是 MyReal。e.Value 是具有新值的字符串。从字符串创建新的 MyReal 后,e.Value 设置正确。RowIndex 和 ColumnIndex 是正确的。ReadOnly 设置为 false。
但是,当我离开单元格时,系统会将原始值恢复到单元格。我认为 UpdateCellValue 会替换 dataSource 中的值,但我似乎遗漏了一些东西。
我错过了什么?
谢谢,马克斯