Advertisement:

Skystone Software

http://www.SkystoneSoftware.com

Scott Waletzko's Blog
Binding Typed Datasets to a DataGrid
Published: 11/3/2008
XMl / RSS

I've always stayed away from databinding - it's never seemed to really serve all of my needs and so I just rolled my own data interfaces. I also learned a whole lot about the data access methods in various programming languages since I didn't take advantage of the drag / drop UI shortcuts.

Lately I've gotten tired of doing too much work, however, and started testing the limits of .NET's latest data binding features. The examples in this post are from .NET 2005, I have no doubt that the latest version of Visual Studio is even more powerful.

I decided to push data binding to the limits right off the bat by seeing what it would take to populate a DataGrid with records of data hoping that the various cell controls would properly display depending on the datatype of the underlying field. If you create a DataSet from an Xml document and then plop it in the grid, it will display your data and make it easily editable, but won't perform type validation (Booleans as Checkboxes, etc). You can, however, make your DataSet typed by applying an Xml Schema to it. Doing so will instruct the DataGrid (via the DataSet's properties) how to display the various inputs. Here's the code:

VB:
Public Class Form1 
	Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) 
		MyBase.OnLoad(e) 
		Dim items As New System.Data.DataSet() 
		items.ReadXmlSchema("C:\temp\items.xsd") 
		items.ReadXml("C:\temp\items.xml") 
		Me.DataGridView1.DataSource = items 
		Me.DataGridView1.DataMember = "item" 
	End Sub 
	Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click 
		CType(Me.DataGridView1.DataSource, System.Data.DataSet).Tables(0).WriteXml("C:\temp\items.xml") 
	End Sub 
End Class 
	
VB:
public class Form1
{
	protected override void OnLoad(System.EventArgs e)
	{
		base.OnLoad(e);
		System.Data.DataSet items = new System.Data.DataSet();
		items.ReadXmlSchema("C:\\temp\\items.xsd");
		items.ReadXml("C:\\temp\\items.xml");
		this.DataGridView1.DataSource = items;
		this.DataGridView1.DataMember = "item";
	}
	private void btnUpdate_Click(object sender, System.EventArgs e)
	{
		((System.Data.DataSet)this.DataGridView1.DataSource).Tables[0].WriteXml("C:\\temp\\items.xml");
	}
}
	

At first glance this is pretty cool, but one limitation I found is that the DataSet can't expose enumerated values. For example, if you define a field in your Xml document as an enum with a list of possible values, it won't display automatically as a ComboBox. Other than that, it's pretty easy to be able to display typed data with very little code.



Questions or Comments? .

VB to C# and C# to VB translation provided by Instant C# and Instant VB.