Custom formatter

I have to do databinding to a custom object. This custom object has an int property which must be databinded to a textbox with a special format (it's for chess squares, so 0 means "a1", 1 means "a2" , ... , 63 means "h8"). And the databinding must be two-way (editing the textbox will update the int property). I'm not sure how to do this: I have to implement my own IFormatProvider? Are there any other ways?
Thanks,
Valentin iliescu
[446 byte] By [viliescu] at [2008-2-15]
# 1

It seems like adding Format and Parse event handlers to your text control's Binding would accomplish what you want.

If you are working in Visual Studio 2005, take a look at the MaskedTextBox. You can use this control to format data, and if you implement a MaskDescriptor for your type, the MaskedTextBox's Input Mask dialog will support your type at design time.

durstin at 2007-9-8 > top of Msdn Tech,Windows Forms,Windows Forms Data Controls and Databinding...
# 2

As Durstin suggested, you can use Format/Parse events as the sample below shows. You can also package this conversion up into a TypeConverter and put a TypeConverter attribute on your property. This provides a better separation between your UI and display logic however there is a bug in B2 (being fixed) where TypeConverters are not honored for properties so I have not included that sample.

Joe


private void Form1_Load(object sender, EventArgs e)
{
List<string> squares = new List<string>();

for (char jdx = 'a'; jdx <= 'h'; jdx++)
{
for (int idx = 1; idx <= 8; idx++)
{
squares.Add(jdx.ToString() + idx.ToString());
}
}

ChessPiece cp = new ChessPiece();
Binding b = new Binding("Text", cp, "Position", true);

b.Format += delegate(object fSender, ConvertEventArgs fArgs)
{
fArgs.Value = squares[(int)fArgs.Value];
};

b.Parse += delegate(object pSender, ConvertEventArgs pArgs)
{
pArgs.Value = squares.IndexOf(pArgs.Value as string);
};

this.textBox1.DataBindings.Add(b);
}

JoeStegman at 2007-9-8 > top of Msdn Tech,Windows Forms,Windows Forms Data Controls and Databinding...
# 3

Where can I find some doc about MaskDescriptor.
I looked at the IPv5 sample and I don't really see how it works.

Thanks in advance,
Philippe

tralala at 2007-9-8 > top of Msdn Tech,Windows Forms,Windows Forms Data Controls and Databinding...