InvalidCastException in DataGridView

(Using VS 2010 Beta 2-.Net 4.0 B2 Rel)

I have a MyTable class derived from a BindingList, where S is a structure. S consists of several other structures, for example:

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, I use MyTable as the binding source for the DataGridView. I can easily load a data grid using InitFromString in separate fields in MyStruct.

The problem occurs when I try to change a value in a DataGridView cell. Going to the first row, in the first column, I change the value of an existing number. This gives a blizzard exception, the first line of which reads:

System.FormatException: Invalid listing from 'System.String' to 'MyReal'

I have looked through discussions and guides, but I don't see any obvious problems.

Any ideas?

+3
3

CellParsing, . -, :

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

I () , 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 , , ?

0

GridValueGroup, ObjValue, ToString. CellParsing :

  • modifies e.Value(which has the type stringinitially, a DesiredType- GridValueGroup) to become the desired type.

This way I avoid creating a new object because the cell already has this object.

It also stores the entered value in the data source. Not sure if it blocks other events ( CellValueChangedyou need to handle it sometimes after parsing the value).

     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;

    }
0
source

Source: https://habr.com/ru/post/1738404/


All Articles