2010-03-24 25 views
3

(使用VS 2010年版2 - .NET 4.0 B2相对)InvalidCastException的在DataGridView中

我有一个类,MyTable的,从的BindingList其中S是一个结构的。 S被由其他几个结构中,例如:

public class MyTable<S>:BindingList<S> where S: struct 
{ 
    ... 
} 

public struct MyStruct 
{ 
    public MyReal r1; 
    public MyReal r2; 

    public MyReal R1 {get{...} set{...}} 
    public MyReal R2 {get{...} set{...}} 

    ... 
} 

public struct MyReal 
{ 
    private Double d; 

    private void InitFromString(string) {this.d = ...;} 

    public MyReal(Double d) { this.d = d;} 
    public MyReal(string val) { this.d = default(Double); InitFromString(val);} 

    public override string ToString() { return this.real.ToString();} 
    public static explicit operator MyReal(string s) { return new MyReal(s);} 
    public static implicit operator String(MyReal r) { return r.ToString();} 
    ... 
} 

OK,我用的是MyTable的作为一个DataGridView绑定源。我可以使用InitFromString在MyStruct中的各个字段上轻松加载数据网格。

当我尝试编辑DataGridView的单元格中的值时,问题就出现了。去第一行,第一列,我改变现有数字的值。它给出了一个例外暴风雪,第一行,其中说:

System.FormatException:从

我已经看过了铸造的讨论和参考书,但不要“System.String”到“MyReal”投无效没有看到任何明显的问题。

任何想法?

+0

这是一个System.FormatException,而不是一个InvalidCastException?检查堆栈跟踪,抛出异常是什么? – Tanzelax 2010-03-24 21:01:20

+0

也许是因为你的操作符从字符串转换为实数是明确的而不是隐式的? – Ikaso 2010-03-25 09:29:51

+0

这都是例外。默认错误对话框报告' System.FormatException:从'System.String' 转换为'MyReal'无效转换 - > System.InvalidCastException: 从'系统'无效转换。字符串'到'MyReal' – 2010-03-26 18:37:11

回答

0

我(几乎)通过处理CellParsing事件来解决这个问题,例如,

private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e) 
{ 
    ... // (checking goes here) 
    e.Value = new MyReal(e.Value.ToString()); 
    e.ParsingApplied = true; 
} 

e.Value被正确设置,但DataGridView仍显示旧值。新值如何被放置在BindingList中?

我是否需要一个明确的方法调用来强制新值进入BindingList,如果有,在哪里?

3

我试过你的方法处理CellParsing,它的工作。虽然我不同做了一点点,处理任何类型:

private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e) 
    { 
     e.Value = Activator.CreateInstance(e.DesiredType, new object[] { e.Value }); 
     e.ParsingApplied = true; 
    } 
0

我的栅格单元都充满了GridValueGroup类型的对象,他们有由ToString覆盖显示ObjValue财产。

  1. 填充细胞值和
  2. 修改e.Value(这是string类型的最初而DesiredTypeGridValueGroup)成为:当修改所述网格单元的字符串,则CellParsing事件由处理所需的类型。

这样我避免了创建一个新的对象,因为单元格已经有了这个对象。

此外,它将输入的值保存在数据源中。不确定是否阻止其他事件(CellValueChanged必须在解析该值后处理)。

 private void grid_CellParsing(object sender, DataGridViewCellParsingEventArgs e) { 
     string val = e.Value.ToString(); 

     DataGridViewCell cell = this.dgvGroup1[e.ColumnIndex, e.RowIndex]; 

     if (e.DesiredType == typeof(GridValueGroup)) 
     { 
      ((GridValueGroup)cell.Value).ObjValue = val; 
      e.Value = ((GridValueGroup)cell.Value); 
     } 
     e.ParsingApplied = true; 

    }