Convert hhmm DataGridView cell value to TimeSpan field

I want to display the TimeSpan field in the DataGridView column as hhmm . And allow the user to edit it in this format. As I understand it, I need to add some logic to the CellFormatting, CellParsing and CellValidating events . Therefore, I think I should check the column name and process it for those that require it.

But how else can I better solve this in order to reuse the code? Can I create my own DataGridViewColumn class, where can I put this logic? How will this be achieved? I do not see any events that exist for the DataGridViewColumn class, so I'm not quite sure what to do here.

+3
source share
2 answers

I would look at a property DataGridViewColumn.CellTemplatethat has this type:

public abstract class DataGridViewCell : DataGridViewElement, ICloneable, IDisposable

possessing these interesting properties:

Value: object
ValueType: Type
ValueTypeConverter: TypeConverter

I would look at the class TypeConverter.

Hope this helps, that I could pack about 2 minutes after ILSpy .

0
source

, , , . . , - TimeSpan, ToString ( ) Parse (String), , . , , Parse, DataGrread DataError. :

class TimeSpanDecorator
{
    protected TimeSpan timeSpan;
    public TimeSpanDecorator(TimeSpan ts)
    {
        timeSpan = ts;
    }
    public override string ToString() // return required TimeSpan view
    {
        return timeSpan.Hours + ":" + timeSpan.Minutes;
    }
    public static TimeSpanDecorator Parse(String value) // parse entered value in any way you want
    {
        String[] parts = value.Split(':');
        if (parts.Length != 2)
            throw new ArgumentException("Wrong format");
        int hours = Int32.Parse(parts[0]);
        int minutes = Int32.Parse(parts[1]);
        TimeSpanDecorator result = new TimeSpanDecorator(new TimeSpan(hours, minutes, 0));
        if (result.timeSpan.Ticks < 0)
            throw new ArgumentException("You should provide positive time value");
        return result;
    }
    //other members
}

internal partial class MainForm : Form
{
    (...)
    private void dataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        MessageBox.Show("Error occured: " + e.Exception.Message, "Warning!"); // showing generated argument exception
        e.ThrowException = false; // telling form that we have processed the error
    }
}

, .

0

All Articles