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.
public Form1() { InitializeComponent(); } DataSet data = new DataSet(); private void Form1_Load(object sender, EventArgs e) { data.ReadXml("data.xml"); textBox1.DataBindings.Add("Text", data.Tables[0], "GuidField"); }
dataset file looks like this
<NewDataSet> <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="GuidTable"> <xs:complexType> <xs:sequence> <xs:element name="GuidField" msdata:DataType="System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <GuidTable><GuidField>b96dbb04-ba71-4353-9dfc-4f87b59b1bb8</GuidField></GuidTable> </NewDataSet>
So we have table GuidTable with one field GuidField and one record.
After running the program all looks very fine :
But…
lets make change in Guid value
and tab out from textBox1, we are back on initial value:
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.
DataRowView CurrentRow; private void textBox1_Leave(object sender, EventArgs e) { if (BindingContext[data.Tables[0]].Position > -1) { CurrentRow = (DataRowView)(BindingContext[data.Tables[0]].Current); if (!string.IsNullOrEmpty(textBox1.Text)) { try { CurrentRow["GuidField"] = Guid.Parse(textBox1.Text); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } else { CurrentRow = null; } }
Now tab out will have needed result:
And inserting faulty value gives 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.