C#: Binding strucutured data to grid

08 Nov

It is not rare that one need to read structured data from files like

x1 y1 z1

Surely you can read it to memory using StreamReader, and the Readline method etc, however this is cumbersome.

C# provides an easy way to to this:

public static DataView ReadCommandSet(string CmdSetFile)

DataSet set1 = new DataSet();

// Get a DataView of the table contained in the dataset.
DataTableCollection tables = set1.Tables;
DataView view1 = new DataView(tables[0]);

return view1;

The DataView can be then bound to a DataGridView

CmdBindingSource.DataSource = ReadCommandSet(…);
CmdDataGridView.DataSource = CmdBindingSource;
CmdDataGridView.Columns[0].Width = 200;
CmdDataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

To filter the data:

CmdBindingSource.Filter = “SomeColumnName LIKE ‘*KeyWords*’ “;

One more question, if the original text is in a txt or other format, then what? Well, there are a lot of tools to convert them to XML files, say for instance, Altova XML tools. You can import the file, view in the grid mode, and then give the data column some tags, such as “X”, “Y” and “Z”, which will be used in the XML for the description of the data.

The benifit of such processing is that you don’t need to implement the IBindingListView interface support filtering, which costs tens of lines of code. This is neat, isn’t it?

1 Comment

Posted by on November 8, 2008 in Dotnet/C#


One response to “C#: Binding strucutured data to grid

  1. xinyustudio

    January 19, 2009 at 11:16 pm

    Note that:

    DataSet CmdDataSet = new DataSet();
    BindingSource CmdBindingSource = new BindingSource();
    CmdBindingSource.DataSource = CmdDataSet;

    Still can be bound to a gird cotnrol, however,
    CmdBindingSource.Filter = “…” does not work!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: