c# – Binding Textbox to System.Guid field

By | 12. November 2016

Today we look a bit closer on using Guid fields and binding them to edit controls.

Binding itself is easy.

For simple test let’s load dataset from file data.xml and bind and  and it to TextBox on screen. For simplicity data file is located on program’s  rood directory, so no full path given.

dataset file looks like this

So we have table GuidTable with one field GuidField and one record.

After running the program all looks very fine :

guid editor

But…

lets make change in Guid value

guideditor

and tab out from textBox1, we are back on initial value:

guid editor

As the datacolumn’s datatype is System.Guid and binded TextBox.Text is string the conversion fails.

What can be done?  If we have only few controls with this issue then one simple way to handle the value conversion using OnLeave event.

 

Now tab out will have needed result:

guideditor

And inserting faulty value gives error:

GUID validation error

 

If same issue must be solved in many cases then consider custom control inherited form TextBox what will internally handle the string to guid conversion.

If you need generated Guid value then use

Guid guid = Guid.NewGuid();

or

String guid = Guid.NewGuid().ToString();

both use the Guid class, the first creates a Guid Object, the second a Guid string.

 

 

 

Leave a Reply